| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.plugin import CheckerPluginInterface, MethodSigContext, Plugin |
| 6 |
from mypy.types import CallableType, Instance, Type, get_proper_type |
| 7 |
|
| 8 |
|
| 9 |
class MethodSigPlugin(Plugin): |
| 10 |
def get_method_signature_hook( |
| 11 |
self, fullname: str |
| 12 |
) -> Callable[[MethodSigContext], CallableType] | None: |
| 13 |
# Ensure that all names are fully qualified |
| 14 |
assert not fullname.endswith(" of Foo") |
| 15 |
|
| 16 |
if fullname.startswith("__main__.Foo."): |
| 17 |
return my_hook |
| 18 |
|
| 19 |
return None |
| 20 |
|
| 21 |
|
| 22 |
def _str_to_int(api: CheckerPluginInterface, typ: Type) -> Type: |
| 23 |
typ = get_proper_type(typ) |
| 24 |
if isinstance(typ, Instance): |
| 25 |
if typ.type.fullname == "builtins.str": |
| 26 |
return api.named_generic_type("builtins.int", []) |
| 27 |
elif typ.args: |
| 28 |
return typ.copy_modified(args=[_str_to_int(api, t) for t in typ.args]) |
| 29 |
|
| 30 |
return typ |
| 31 |
|
| 32 |
|
| 33 |
def my_hook(ctx: MethodSigContext) -> CallableType: |
| 34 |
return ctx.default_signature.copy_modified( |
| 35 |
arg_types=[_str_to_int(ctx.api, t) for t in ctx.default_signature.arg_types], |
| 36 |
ret_type=_str_to_int(ctx.api, ctx.default_signature.ret_type), |
| 37 |
) |
| 38 |
|
| 39 |
|
| 40 |
def plugin(version: str) -> type[MethodSigPlugin]: |
| 41 |
return MethodSigPlugin |