| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.plugin import CheckerPluginInterface, MethodContext, MethodSigContext, Plugin |
| 6 |
from mypy.types import CallableType, Instance, Type, get_proper_type |
| 7 |
|
| 8 |
|
| 9 |
class MethodPlugin(Plugin): |
| 10 |
def get_method_signature_hook( |
| 11 |
self, fullname: str |
| 12 |
) -> Callable[[MethodSigContext], CallableType] | None: |
| 13 |
if fullname.startswith("__main__.Foo."): |
| 14 |
return my_meth_sig_hook |
| 15 |
return None |
| 16 |
|
| 17 |
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: |
| 18 |
if fullname.startswith("__main__.Bar."): |
| 19 |
return my_meth_hook |
| 20 |
return None |
| 21 |
|
| 22 |
|
| 23 |
def _str_to_int(api: CheckerPluginInterface, typ: Type) -> Type: |
| 24 |
typ = get_proper_type(typ) |
| 25 |
if isinstance(typ, Instance): |
| 26 |
if typ.type.fullname == "builtins.str": |
| 27 |
return api.named_generic_type("builtins.int", []) |
| 28 |
elif typ.args: |
| 29 |
return typ.copy_modified(args=[_str_to_int(api, t) for t in typ.args]) |
| 30 |
return typ |
| 31 |
|
| 32 |
|
| 33 |
def _float_to_int(api: CheckerPluginInterface, typ: Type) -> Type: |
| 34 |
typ = get_proper_type(typ) |
| 35 |
if isinstance(typ, Instance): |
| 36 |
if typ.type.fullname == "builtins.float": |
| 37 |
return api.named_generic_type("builtins.int", []) |
| 38 |
elif typ.args: |
| 39 |
return typ.copy_modified(args=[_float_to_int(api, t) for t in typ.args]) |
| 40 |
return typ |
| 41 |
|
| 42 |
|
| 43 |
def my_meth_sig_hook(ctx: MethodSigContext) -> CallableType: |
| 44 |
return ctx.default_signature.copy_modified( |
| 45 |
arg_types=[_str_to_int(ctx.api, t) for t in ctx.default_signature.arg_types], |
| 46 |
ret_type=_str_to_int(ctx.api, ctx.default_signature.ret_type), |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
def my_meth_hook(ctx: MethodContext) -> Type: |
| 51 |
return _float_to_int(ctx.api, ctx.default_return_type) |
| 52 |
|
| 53 |
|
| 54 |
def plugin(version: str) -> type[MethodPlugin]: |
| 55 |
return MethodPlugin |