Debian Codegraph @

pyvista/typing/mypy_plugin.py

raw
1 """PyVista plugin for static type-checking with mypy."""
2
3 from __future__ import annotations
4
5 __all__: list[str] = ['promote_type']
6
7 import importlib.util
8 from typing import TYPE_CHECKING
9 from typing import TypeVar
10
11 if TYPE_CHECKING: # pragma: no cover
12 from collections.abc import Callable
13 from typing import Any
14
15 from mypy.plugin import ClassDefContext
16 from mypy.types import Instance
17 from typing_extensions import Self
18
19
20 T = TypeVar('T', bound=type)
21
22
23 def promote_type(*types: type[Any]) -> Callable[[T], T]: # noqa: ARG001
24 """Duck-type type-promotion decorator used by the mypy plugin.
25
26 Apply this decorator to a class to promote its type statically.
27 This tells `mypy` to treat the decorated class as though it's
28 equivalent to another class.
29
30 .. note::
31 This decorator does nothing at runtime and merely passes the object through.
32
33 Parameters
34 ----------
35 types : type
36 Type(s) to promote the class to. The types are only used statically by mypy.
37
38 Returns
39 -------
40 Callable
41 Decorated class.
42
43 """
44 return lambda obj: obj
45
46
47 if importlib.util.find_spec('mypy'): # pragma: no cover
48 from mypy.nodes import CallExpr
49 from mypy.nodes import NameExpr
50 from mypy.nodes import RefExpr
51 from mypy.plugin import Plugin
52
53 def _promote_type_callback(ctx: ClassDefContext) -> None:
54 """Apply the `promote_type` decorator.
55
56 The decorated class is captured and promoted to the type(s) provided
57 by the decorator's argument(s).
58 """
59 for decorator in ctx.cls.decorators:
60 if isinstance(decorator, CallExpr):
61 callee = decorator.callee
62 if isinstance(callee, NameExpr):
63 name = callee.name
64 if name == promote_type.__name__:
65 decorated_type: Instance = ctx.api.named_type(ctx.cls.fullname)
66 args = decorator.args
67 for arg in args:
68 if isinstance(arg, RefExpr):
69 named_type: Instance = ctx.api.named_type(arg.fullname)
70 decorated_type.type._promote.append(named_type)
71
72 class _PyVistaPlugin(Plugin):
73 """Mypy plugin to enable static type promotions."""
74
75 def get_class_decorator_hook(
76 self: Self, fullname: str
77 ) -> Callable[[ClassDefContext], None] | None:
78 def _get_type_fullname(typ: Any) -> str:
79 return f'{typ.__module__}.{typ.__qualname__}'
80
81 if fullname == _get_type_fullname(promote_type):
82 return _promote_type_callback
83 return None
84
85 def plugin(version: str) -> type[_PyVistaPlugin]: # numpydoc ignore: RT01 # noqa: ARG001
86 """Entry-point for mypy."""
87 return _PyVistaPlugin