Debian Codegraph @

test-data/unit/plugins/attrhook2.py

raw
1 from __future__ import annotations
2
3 from typing import Callable
4
5 from mypy.plugin import AttributeContext, Plugin
6 from mypy.types import AnyType, Type, TypeOfAny
7
8
9 class AttrPlugin(Plugin):
10 def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
11 if fullname == "m.Magic.magic_field":
12 return magic_field_callback
13 if fullname == "m.Magic.nonexistent_field":
14 return nonexistent_field_callback
15 if fullname == "m.Magic.no_assignment_field":
16 return no_assignment_field_callback
17 return None
18
19
20 def magic_field_callback(ctx: AttributeContext) -> Type:
21 return ctx.api.named_generic_type("builtins.str", [])
22
23
24 def nonexistent_field_callback(ctx: AttributeContext) -> Type:
25 ctx.api.fail("Field does not exist", ctx.context)
26 return AnyType(TypeOfAny.from_error)
27
28
29 def no_assignment_field_callback(ctx: AttributeContext) -> Type:
30 if ctx.is_lvalue:
31 ctx.api.fail(f"Cannot assign to field", ctx.context)
32 return AnyType(TypeOfAny.from_error)
33 return ctx.default_attr_type
34
35
36 def plugin(version: str) -> type[AttrPlugin]:
37 return AttrPlugin