| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.plugin import MethodContext, Plugin |
| 6 |
from mypy.types import Instance, Type |
| 7 |
|
| 8 |
|
| 9 |
class CallableInstancePlugin(Plugin): |
| 10 |
def get_function_hook(self, fullname: str) -> None: |
| 11 |
assert not fullname.endswith(" of Foo") |
| 12 |
|
| 13 |
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: |
| 14 |
# Ensure that all names are fully qualified |
| 15 |
assert not fullname.endswith(" of Foo") |
| 16 |
|
| 17 |
if fullname == "__main__.Class.__call__": |
| 18 |
return my_hook |
| 19 |
|
| 20 |
return None |
| 21 |
|
| 22 |
|
| 23 |
def my_hook(ctx: MethodContext) -> Type: |
| 24 |
if isinstance(ctx.type, Instance) and len(ctx.type.args) == 1: |
| 25 |
return ctx.type.args[0] |
| 26 |
return ctx.default_return_type |
| 27 |
|
| 28 |
|
| 29 |
def plugin(version: str) -> type[CallableInstancePlugin]: |
| 30 |
return CallableInstancePlugin |