| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.nodes import ARG_POS, Argument, Var |
| 6 |
from mypy.plugin import ClassDefContext, Plugin |
| 7 |
from mypy.plugins.common import MethodSpec, add_overloaded_method_to_class |
| 8 |
|
| 9 |
|
| 10 |
class OverloadedMethodPlugin(Plugin): |
| 11 |
def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: |
| 12 |
if "AddOverloadedMethod" in fullname: |
| 13 |
return add_overloaded_method_hook |
| 14 |
return None |
| 15 |
|
| 16 |
|
| 17 |
def add_overloaded_method_hook(ctx: ClassDefContext) -> None: |
| 18 |
add_overloaded_method_to_class(ctx.api, ctx.cls, "method", _generate_method_specs(ctx)) |
| 19 |
add_overloaded_method_to_class( |
| 20 |
ctx.api, ctx.cls, "clsmethod", _generate_method_specs(ctx), is_classmethod=True |
| 21 |
) |
| 22 |
add_overloaded_method_to_class( |
| 23 |
ctx.api, ctx.cls, "stmethod", _generate_method_specs(ctx), is_staticmethod=True |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
def _generate_method_specs(ctx: ClassDefContext) -> list[MethodSpec]: |
| 28 |
return [ |
| 29 |
MethodSpec( |
| 30 |
args=[Argument(Var("arg"), ctx.api.named_type("builtins.int"), None, ARG_POS)], |
| 31 |
return_type=ctx.api.named_type("builtins.str"), |
| 32 |
), |
| 33 |
MethodSpec( |
| 34 |
args=[Argument(Var("arg"), ctx.api.named_type("builtins.str"), None, ARG_POS)], |
| 35 |
return_type=ctx.api.named_type("builtins.int"), |
| 36 |
), |
| 37 |
] |
| 38 |
|
| 39 |
|
| 40 |
def plugin(version: str) -> type[OverloadedMethodPlugin]: |
| 41 |
return OverloadedMethodPlugin |