| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.nodes import StrExpr |
| 6 |
from mypy.plugin import FunctionContext, MethodContext, Plugin |
| 7 |
from mypy.types import Type |
| 8 |
|
| 9 |
|
| 10 |
class ArgNamesPlugin(Plugin): |
| 11 |
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: |
| 12 |
if fullname in { |
| 13 |
"mod.func", |
| 14 |
"mod.func_unfilled", |
| 15 |
"mod.func_star_expr", |
| 16 |
"mod.ClassInit", |
| 17 |
"mod.Outer.NestedClassInit", |
| 18 |
}: |
| 19 |
return extract_classname_and_set_as_return_type_function |
| 20 |
return None |
| 21 |
|
| 22 |
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: |
| 23 |
if fullname in { |
| 24 |
"mod.Class.method", |
| 25 |
"mod.Class.myclassmethod", |
| 26 |
"mod.Class.mystaticmethod", |
| 27 |
"mod.ClassUnfilled.method", |
| 28 |
"mod.ClassStarExpr.method", |
| 29 |
"mod.ClassChild.method", |
| 30 |
"mod.ClassChild.myclassmethod", |
| 31 |
}: |
| 32 |
return extract_classname_and_set_as_return_type_method |
| 33 |
return None |
| 34 |
|
| 35 |
|
| 36 |
def extract_classname_and_set_as_return_type_function(ctx: FunctionContext) -> Type: |
| 37 |
arg = ctx.args[ctx.callee_arg_names.index("classname")][0] |
| 38 |
if not isinstance(arg, StrExpr): |
| 39 |
return ctx.default_return_type |
| 40 |
return ctx.api.named_generic_type(arg.value, []) |
| 41 |
|
| 42 |
|
| 43 |
def extract_classname_and_set_as_return_type_method(ctx: MethodContext) -> Type: |
| 44 |
arg = ctx.args[ctx.callee_arg_names.index("classname")][0] |
| 45 |
if not isinstance(arg, StrExpr): |
| 46 |
return ctx.default_return_type |
| 47 |
return ctx.api.named_generic_type(arg.value, []) |
| 48 |
|
| 49 |
|
| 50 |
def plugin(version: str) -> type[ArgNamesPlugin]: |
| 51 |
return ArgNamesPlugin |