| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.plugin import MethodContext, MethodSigContext, Plugin |
| 6 |
from mypy.types import CallableType, NoneType, Type, get_proper_type |
| 7 |
|
| 8 |
|
| 9 |
class DescriptorPlugin(Plugin): |
| 10 |
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: |
| 11 |
if fullname == "__main__.Desc.__get__": |
| 12 |
return get_hook |
| 13 |
return None |
| 14 |
|
| 15 |
def get_method_signature_hook( |
| 16 |
self, fullname: str |
| 17 |
) -> Callable[[MethodSigContext], CallableType] | None: |
| 18 |
if fullname == "__main__.Desc.__set__": |
| 19 |
return set_hook |
| 20 |
return None |
| 21 |
|
| 22 |
|
| 23 |
def get_hook(ctx: MethodContext) -> Type: |
| 24 |
arg = get_proper_type(ctx.arg_types[0][0]) |
| 25 |
if isinstance(arg, NoneType): |
| 26 |
return ctx.api.named_generic_type("builtins.str", []) |
| 27 |
return ctx.api.named_generic_type("builtins.int", []) |
| 28 |
|
| 29 |
|
| 30 |
def set_hook(ctx: MethodSigContext) -> CallableType: |
| 31 |
return CallableType( |
| 32 |
[ |
| 33 |
ctx.api.named_generic_type("__main__.Cls", []), |
| 34 |
ctx.api.named_generic_type("builtins.int", []), |
| 35 |
], |
| 36 |
ctx.default_signature.arg_kinds, |
| 37 |
ctx.default_signature.arg_names, |
| 38 |
ctx.default_signature.ret_type, |
| 39 |
ctx.default_signature.fallback, |
| 40 |
) |
| 41 |
|
| 42 |
|
| 43 |
def plugin(version: str) -> type[DescriptorPlugin]: |
| 44 |
return DescriptorPlugin |