| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
from mypy.nodes import NameExpr |
| 6 |
from mypy.plugin import FunctionContext, Plugin |
| 7 |
from mypy.types import Instance, NoneType, Type, UnionType, get_proper_type |
| 8 |
|
| 9 |
|
| 10 |
class AttrPlugin(Plugin): |
| 11 |
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: |
| 12 |
if fullname.startswith("mod.Attr"): |
| 13 |
return attr_hook |
| 14 |
return None |
| 15 |
|
| 16 |
|
| 17 |
def attr_hook(ctx: FunctionContext) -> Type: |
| 18 |
default = get_proper_type(ctx.default_return_type) |
| 19 |
assert isinstance(default, Instance) |
| 20 |
if default.type.fullname == "mod.Attr": |
| 21 |
attr_base = default |
| 22 |
else: |
| 23 |
attr_base = None |
| 24 |
for base in default.type.bases: |
| 25 |
if base.type.fullname == "mod.Attr": |
| 26 |
attr_base = base |
| 27 |
break |
| 28 |
assert attr_base is not None |
| 29 |
last_arg_exprs = ctx.args[-1] |
| 30 |
if any(isinstance(expr, NameExpr) and expr.name == "True" for expr in last_arg_exprs): |
| 31 |
return attr_base |
| 32 |
assert len(attr_base.args) == 1 |
| 33 |
arg_type = attr_base.args[0] |
| 34 |
return Instance( |
| 35 |
attr_base.type, |
| 36 |
[UnionType([arg_type, NoneType()])], |
| 37 |
line=default.line, |
| 38 |
column=default.column, |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
def plugin(version: str) -> type[AttrPlugin]: |
| 43 |
return AttrPlugin |