File: descriptor.py

package info (click to toggle)
mypy 1.19.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,412 kB
  • sloc: python: 114,754; ansic: 13,343; cpp: 11,380; makefile: 257; sh: 28
file content (44 lines) | stat: -rw-r--r-- 1,352 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from __future__ import annotations

from typing import Callable

from mypy.plugin import MethodContext, MethodSigContext, Plugin
from mypy.types import CallableType, NoneType, Type, get_proper_type


class DescriptorPlugin(Plugin):
    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
        if fullname == "__main__.Desc.__get__":
            return get_hook
        return None

    def get_method_signature_hook(
        self, fullname: str
    ) -> Callable[[MethodSigContext], CallableType] | None:
        if fullname == "__main__.Desc.__set__":
            return set_hook
        return None


def get_hook(ctx: MethodContext) -> Type:
    arg = get_proper_type(ctx.arg_types[0][0])
    if isinstance(arg, NoneType):
        return ctx.api.named_generic_type("builtins.str", [])
    return ctx.api.named_generic_type("builtins.int", [])


def set_hook(ctx: MethodSigContext) -> CallableType:
    return CallableType(
        [
            ctx.api.named_generic_type("__main__.Cls", []),
            ctx.api.named_generic_type("builtins.int", []),
        ],
        ctx.default_signature.arg_kinds,
        ctx.default_signature.arg_names,
        ctx.default_signature.ret_type,
        ctx.default_signature.fallback,
    )


def plugin(version: str) -> type[DescriptorPlugin]:
    return DescriptorPlugin