mypy_plugin.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. """A mypy_ plugin for managing a number of platform-specific annotations.
  2. Its functionality can be split into three distinct parts:
  3. * Assigning the (platform-dependent) precisions of certain `~numpy.number`
  4. subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and
  5. `~numpy.longlong`. See the documentation on
  6. :ref:`scalar types <arrays.scalars.built-in>` for a comprehensive overview
  7. of the affected classes. Without the plugin the precision of all relevant
  8. classes will be inferred as `~typing.Any`.
  9. * Removing all extended-precision `~numpy.number` subclasses that are
  10. unavailable for the platform in question. Most notably this includes the
  11. likes of `~numpy.float128` and `~numpy.complex256`. Without the plugin *all*
  12. extended-precision types will, as far as mypy is concerned, be available
  13. to all platforms.
  14. * Assigning the (platform-dependent) precision of `~numpy.ctypeslib.c_intp`.
  15. Without the plugin the type will default to `ctypes.c_int64`.
  16. .. versionadded:: 1.22
  17. Examples
  18. --------
  19. To enable the plugin, one must add it to their mypy `configuration file`_:
  20. .. code-block:: ini
  21. [mypy]
  22. plugins = numpy.typing.mypy_plugin
  23. .. _mypy: http://mypy-lang.org/
  24. .. _configuration file: https://mypy.readthedocs.io/en/stable/config_file.html
  25. """
  26. from __future__ import annotations
  27. from collections.abc import Iterable
  28. from typing import Final, TYPE_CHECKING, Callable
  29. import numpy as np
  30. try:
  31. import mypy.types
  32. from mypy.types import Type
  33. from mypy.plugin import Plugin, AnalyzeTypeContext
  34. from mypy.nodes import MypyFile, ImportFrom, Statement
  35. from mypy.build import PRI_MED
  36. _HookFunc = Callable[[AnalyzeTypeContext], Type]
  37. MYPY_EX: None | ModuleNotFoundError = None
  38. except ModuleNotFoundError as ex:
  39. MYPY_EX = ex
  40. __all__: list[str] = []
  41. def _get_precision_dict() -> dict[str, str]:
  42. names = [
  43. ("_NBitByte", np.byte),
  44. ("_NBitShort", np.short),
  45. ("_NBitIntC", np.intc),
  46. ("_NBitIntP", np.intp),
  47. ("_NBitInt", np.int_),
  48. ("_NBitLongLong", np.longlong),
  49. ("_NBitHalf", np.half),
  50. ("_NBitSingle", np.single),
  51. ("_NBitDouble", np.double),
  52. ("_NBitLongDouble", np.longdouble),
  53. ]
  54. ret = {}
  55. for name, typ in names:
  56. n: int = 8 * typ().dtype.itemsize
  57. ret[f'numpy._typing._nbit.{name}'] = f"numpy._{n}Bit"
  58. return ret
  59. def _get_extended_precision_list() -> list[str]:
  60. extended_types = [np.ulonglong, np.longlong, np.longdouble, np.clongdouble]
  61. extended_names = {
  62. "uint128",
  63. "uint256",
  64. "int128",
  65. "int256",
  66. "float80",
  67. "float96",
  68. "float128",
  69. "float256",
  70. "complex160",
  71. "complex192",
  72. "complex256",
  73. "complex512",
  74. }
  75. return [i.__name__ for i in extended_types if i.__name__ in extended_names]
  76. def _get_c_intp_name() -> str:
  77. # Adapted from `np.core._internal._getintp_ctype`
  78. char = np.dtype('p').char
  79. if char == 'i':
  80. return "c_int"
  81. elif char == 'l':
  82. return "c_long"
  83. elif char == 'q':
  84. return "c_longlong"
  85. else:
  86. return "c_long"
  87. #: A dictionary mapping type-aliases in `numpy._typing._nbit` to
  88. #: concrete `numpy.typing.NBitBase` subclasses.
  89. _PRECISION_DICT: Final = _get_precision_dict()
  90. #: A list with the names of all extended precision `np.number` subclasses.
  91. _EXTENDED_PRECISION_LIST: Final = _get_extended_precision_list()
  92. #: The name of the ctypes quivalent of `np.intp`
  93. _C_INTP: Final = _get_c_intp_name()
  94. def _hook(ctx: AnalyzeTypeContext) -> Type:
  95. """Replace a type-alias with a concrete ``NBitBase`` subclass."""
  96. typ, _, api = ctx
  97. name = typ.name.split(".")[-1]
  98. name_new = _PRECISION_DICT[f"numpy._typing._nbit.{name}"]
  99. return api.named_type(name_new)
  100. if TYPE_CHECKING or MYPY_EX is None:
  101. def _index(iterable: Iterable[Statement], id: str) -> int:
  102. """Identify the first ``ImportFrom`` instance the specified `id`."""
  103. for i, value in enumerate(iterable):
  104. if getattr(value, "id", None) == id:
  105. return i
  106. raise ValueError("Failed to identify a `ImportFrom` instance "
  107. f"with the following id: {id!r}")
  108. def _override_imports(
  109. file: MypyFile,
  110. module: str,
  111. imports: list[tuple[str, None | str]],
  112. ) -> None:
  113. """Override the first `module`-based import with new `imports`."""
  114. # Construct a new `from module import y` statement
  115. import_obj = ImportFrom(module, 0, names=imports)
  116. import_obj.is_top_level = True
  117. # Replace the first `module`-based import statement with `import_obj`
  118. for lst in [file.defs, file.imports]: # type: list[Statement]
  119. i = _index(lst, module)
  120. lst[i] = import_obj
  121. class _NumpyPlugin(Plugin):
  122. """A mypy plugin for handling versus numpy-specific typing tasks."""
  123. def get_type_analyze_hook(self, fullname: str) -> None | _HookFunc:
  124. """Set the precision of platform-specific `numpy.number`
  125. subclasses.
  126. For example: `numpy.int_`, `numpy.longlong` and `numpy.longdouble`.
  127. """
  128. if fullname in _PRECISION_DICT:
  129. return _hook
  130. return None
  131. def get_additional_deps(
  132. self, file: MypyFile
  133. ) -> list[tuple[int, str, int]]:
  134. """Handle all import-based overrides.
  135. * Import platform-specific extended-precision `numpy.number`
  136. subclasses (*e.g.* `numpy.float96`, `numpy.float128` and
  137. `numpy.complex256`).
  138. * Import the appropriate `ctypes` equivalent to `numpy.intp`.
  139. """
  140. ret = [(PRI_MED, file.fullname, -1)]
  141. if file.fullname == "numpy":
  142. _override_imports(
  143. file, "numpy._typing._extended_precision",
  144. imports=[(v, v) for v in _EXTENDED_PRECISION_LIST],
  145. )
  146. elif file.fullname == "numpy.ctypeslib":
  147. _override_imports(
  148. file, "ctypes",
  149. imports=[(_C_INTP, "_c_intp")],
  150. )
  151. return ret
  152. def plugin(version: str) -> type[_NumpyPlugin]:
  153. """An entry-point for mypy."""
  154. return _NumpyPlugin
  155. else:
  156. def plugin(version: str) -> type[_NumpyPlugin]:
  157. """An entry-point for mypy."""
  158. raise MYPY_EX