Debian Codegraph @

test-data/unit/plugins/dyn_class_from_method.py

raw
1 from __future__ import annotations
2
3 from typing import Callable
4
5 from mypy.nodes import (
6 GDEF,
7 Block,
8 ClassDef,
9 IndexExpr,
10 MemberExpr,
11 NameExpr,
12 RefExpr,
13 SymbolTable,
14 SymbolTableNode,
15 TypeApplication,
16 TypeInfo,
17 )
18 from mypy.plugin import DynamicClassDefContext, Plugin
19 from mypy.types import Instance
20
21
22 class DynPlugin(Plugin):
23 def get_dynamic_class_hook(
24 self, fullname: str
25 ) -> Callable[[DynamicClassDefContext], None] | None:
26 if "from_queryset" in fullname:
27 return add_info_hook
28 if "as_manager" in fullname:
29 return as_manager_hook
30 return None
31
32
33 def add_info_hook(ctx: DynamicClassDefContext) -> None:
34 class_def = ClassDef(ctx.name, Block([]))
35 class_def.fullname = ctx.api.qualified_name(ctx.name)
36
37 info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)
38 class_def.info = info
39 assert isinstance(ctx.call.args[0], RefExpr)
40 queryset_type_fullname = ctx.call.args[0].fullname
41 queryset_node = ctx.api.lookup_fully_qualified_or_none(queryset_type_fullname)
42 assert queryset_node is not None
43 queryset_info = queryset_node.node
44 assert isinstance(queryset_info, TypeInfo)
45 obj = ctx.api.named_type("builtins.object")
46 info.mro = [info, queryset_info, obj.type]
47 info.bases = [Instance(queryset_info, [])]
48 ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
49
50
51 def as_manager_hook(ctx: DynamicClassDefContext) -> None:
52 class_def = ClassDef(ctx.name, Block([]))
53 class_def.fullname = ctx.api.qualified_name(ctx.name)
54
55 info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)
56 class_def.info = info
57 assert isinstance(ctx.call.callee, MemberExpr)
58 assert isinstance(ctx.call.callee.expr, IndexExpr)
59 assert isinstance(ctx.call.callee.expr.analyzed, TypeApplication)
60 assert isinstance(ctx.call.callee.expr.analyzed.expr, NameExpr)
61
62 queryset_type_fullname = ctx.call.callee.expr.analyzed.expr.fullname
63 queryset_node = ctx.api.lookup_fully_qualified_or_none(queryset_type_fullname)
64 assert queryset_node is not None
65 queryset_info = queryset_node.node
66 assert isinstance(queryset_info, TypeInfo)
67 parameter_type = ctx.call.callee.expr.analyzed.types[0]
68
69 obj = ctx.api.named_type("builtins.object")
70 info.mro = [info, queryset_info, obj.type]
71 info.bases = [Instance(queryset_info, [parameter_type])]
72 ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
73
74
75 def plugin(version: str) -> type[DynPlugin]:
76 return DynPlugin