typing.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
  4. from __future__ import annotations
  5. from typing import TYPE_CHECKING, NamedTuple
  6. import astroid.bases
  7. from astroid import nodes
  8. from pylint.checkers import BaseChecker
  9. from pylint.checkers.utils import (
  10. in_type_checking_block,
  11. is_node_in_type_annotation_context,
  12. is_postponed_evaluation_enabled,
  13. only_required_for_messages,
  14. safe_infer,
  15. )
  16. from pylint.constants import TYPING_NORETURN
  17. from pylint.interfaces import HIGH, INFERENCE
  18. if TYPE_CHECKING:
  19. from pylint.lint import PyLinter
  20. class TypingAlias(NamedTuple):
  21. name: str
  22. name_collision: bool
  23. DEPRECATED_TYPING_ALIASES: dict[str, TypingAlias] = {
  24. "typing.Tuple": TypingAlias("tuple", False),
  25. "typing.List": TypingAlias("list", False),
  26. "typing.Dict": TypingAlias("dict", False),
  27. "typing.Set": TypingAlias("set", False),
  28. "typing.FrozenSet": TypingAlias("frozenset", False),
  29. "typing.Type": TypingAlias("type", False),
  30. "typing.Deque": TypingAlias("collections.deque", True),
  31. "typing.DefaultDict": TypingAlias("collections.defaultdict", True),
  32. "typing.OrderedDict": TypingAlias("collections.OrderedDict", True),
  33. "typing.Counter": TypingAlias("collections.Counter", True),
  34. "typing.ChainMap": TypingAlias("collections.ChainMap", True),
  35. "typing.Awaitable": TypingAlias("collections.abc.Awaitable", True),
  36. "typing.Coroutine": TypingAlias("collections.abc.Coroutine", True),
  37. "typing.AsyncIterable": TypingAlias("collections.abc.AsyncIterable", True),
  38. "typing.AsyncIterator": TypingAlias("collections.abc.AsyncIterator", True),
  39. "typing.AsyncGenerator": TypingAlias("collections.abc.AsyncGenerator", True),
  40. "typing.Iterable": TypingAlias("collections.abc.Iterable", True),
  41. "typing.Iterator": TypingAlias("collections.abc.Iterator", True),
  42. "typing.Generator": TypingAlias("collections.abc.Generator", True),
  43. "typing.Reversible": TypingAlias("collections.abc.Reversible", True),
  44. "typing.Container": TypingAlias("collections.abc.Container", True),
  45. "typing.Collection": TypingAlias("collections.abc.Collection", True),
  46. "typing.Callable": TypingAlias("collections.abc.Callable", True),
  47. "typing.AbstractSet": TypingAlias("collections.abc.Set", False),
  48. "typing.MutableSet": TypingAlias("collections.abc.MutableSet", True),
  49. "typing.Mapping": TypingAlias("collections.abc.Mapping", True),
  50. "typing.MutableMapping": TypingAlias("collections.abc.MutableMapping", True),
  51. "typing.Sequence": TypingAlias("collections.abc.Sequence", True),
  52. "typing.MutableSequence": TypingAlias("collections.abc.MutableSequence", True),
  53. "typing.ByteString": TypingAlias("collections.abc.ByteString", True),
  54. "typing.MappingView": TypingAlias("collections.abc.MappingView", True),
  55. "typing.KeysView": TypingAlias("collections.abc.KeysView", True),
  56. "typing.ItemsView": TypingAlias("collections.abc.ItemsView", True),
  57. "typing.ValuesView": TypingAlias("collections.abc.ValuesView", True),
  58. "typing.ContextManager": TypingAlias("contextlib.AbstractContextManager", False),
  59. "typing.AsyncContextManager": TypingAlias(
  60. "contextlib.AbstractAsyncContextManager", False
  61. ),
  62. "typing.Pattern": TypingAlias("re.Pattern", True),
  63. "typing.Match": TypingAlias("re.Match", True),
  64. "typing.Hashable": TypingAlias("collections.abc.Hashable", True),
  65. "typing.Sized": TypingAlias("collections.abc.Sized", True),
  66. }
  67. ALIAS_NAMES = frozenset(key.split(".")[1] for key in DEPRECATED_TYPING_ALIASES)
  68. UNION_NAMES = ("Optional", "Union")
  69. class DeprecatedTypingAliasMsg(NamedTuple):
  70. node: nodes.Name | nodes.Attribute
  71. qname: str
  72. alias: str
  73. parent_subscript: bool = False
  74. class TypingChecker(BaseChecker):
  75. """Find issue specifically related to type annotations."""
  76. name = "typing"
  77. msgs = {
  78. "W6001": (
  79. "'%s' is deprecated, use '%s' instead",
  80. "deprecated-typing-alias",
  81. "Emitted when a deprecated typing alias is used.",
  82. ),
  83. "R6002": (
  84. "'%s' will be deprecated with PY39, consider using '%s' instead%s",
  85. "consider-using-alias",
  86. "Only emitted if 'runtime-typing=no' and a deprecated "
  87. "typing alias is used in a type annotation context in "
  88. "Python 3.7 or 3.8.",
  89. ),
  90. "R6003": (
  91. "Consider using alternative Union syntax instead of '%s'%s",
  92. "consider-alternative-union-syntax",
  93. "Emitted when 'typing.Union' or 'typing.Optional' is used "
  94. "instead of the alternative Union syntax 'int | None'.",
  95. ),
  96. "E6004": (
  97. "'NoReturn' inside compound types is broken in 3.7.0 / 3.7.1",
  98. "broken-noreturn",
  99. "``typing.NoReturn`` inside compound types is broken in "
  100. "Python 3.7.0 and 3.7.1. If not dependent on runtime introspection, "
  101. "use string annotation instead. E.g. "
  102. "``Callable[..., 'NoReturn']``. https://bugs.python.org/issue34921",
  103. ),
  104. "E6005": (
  105. "'collections.abc.Callable' inside Optional and Union is broken in "
  106. "3.9.0 / 3.9.1 (use 'typing.Callable' instead)",
  107. "broken-collections-callable",
  108. "``collections.abc.Callable`` inside Optional and Union is broken in "
  109. "Python 3.9.0 and 3.9.1. Use ``typing.Callable`` for these cases instead. "
  110. "https://bugs.python.org/issue42965",
  111. ),
  112. "R6006": (
  113. "Type `%s` is used more than once in union type annotation. Remove redundant typehints.",
  114. "redundant-typehint-argument",
  115. "Duplicated type arguments will be skipped by `mypy` tool, therefore should be "
  116. "removed to avoid confusion.",
  117. ),
  118. }
  119. options = (
  120. (
  121. "runtime-typing",
  122. {
  123. "default": True,
  124. "type": "yn",
  125. "metavar": "<y or n>",
  126. "help": (
  127. "Set to ``no`` if the app / library does **NOT** need to "
  128. "support runtime introspection of type annotations. "
  129. "If you use type annotations **exclusively** for type checking "
  130. "of an application, you're probably fine. For libraries, "
  131. "evaluate if some users want to access the type hints "
  132. "at runtime first, e.g., through ``typing.get_type_hints``. "
  133. "Applies to Python versions 3.7 - 3.9"
  134. ),
  135. },
  136. ),
  137. )
  138. _should_check_typing_alias: bool
  139. """The use of type aliases (PEP 585) requires Python 3.9
  140. or Python 3.7+ with postponed evaluation.
  141. """
  142. _should_check_alternative_union_syntax: bool
  143. """The use of alternative union syntax (PEP 604) requires Python 3.10
  144. or Python 3.7+ with postponed evaluation.
  145. """
  146. def __init__(self, linter: PyLinter) -> None:
  147. """Initialize checker instance."""
  148. super().__init__(linter=linter)
  149. self._found_broken_callable_location: bool = False
  150. self._alias_name_collisions: set[str] = set()
  151. self._deprecated_typing_alias_msgs: list[DeprecatedTypingAliasMsg] = []
  152. self._consider_using_alias_msgs: list[DeprecatedTypingAliasMsg] = []
  153. def open(self) -> None:
  154. py_version = self.linter.config.py_version
  155. self._py37_plus = py_version >= (3, 7)
  156. self._py39_plus = py_version >= (3, 9)
  157. self._py310_plus = py_version >= (3, 10)
  158. self._should_check_typing_alias = self._py39_plus or (
  159. self._py37_plus and self.linter.config.runtime_typing is False
  160. )
  161. self._should_check_alternative_union_syntax = self._py310_plus or (
  162. self._py37_plus and self.linter.config.runtime_typing is False
  163. )
  164. self._should_check_noreturn = py_version < (3, 7, 2)
  165. self._should_check_callable = py_version < (3, 9, 2)
  166. def _msg_postponed_eval_hint(self, node: nodes.NodeNG) -> str:
  167. """Message hint if postponed evaluation isn't enabled."""
  168. if self._py310_plus or "annotations" in node.root().future_imports:
  169. return ""
  170. return ". Add 'from __future__ import annotations' as well"
  171. @only_required_for_messages(
  172. "deprecated-typing-alias",
  173. "consider-using-alias",
  174. "consider-alternative-union-syntax",
  175. "broken-noreturn",
  176. "broken-collections-callable",
  177. )
  178. def visit_name(self, node: nodes.Name) -> None:
  179. if self._should_check_typing_alias and node.name in ALIAS_NAMES:
  180. self._check_for_typing_alias(node)
  181. if self._should_check_alternative_union_syntax and node.name in UNION_NAMES:
  182. self._check_for_alternative_union_syntax(node, node.name)
  183. if self._should_check_noreturn and node.name == "NoReturn":
  184. self._check_broken_noreturn(node)
  185. if self._should_check_callable and node.name == "Callable":
  186. self._check_broken_callable(node)
  187. @only_required_for_messages(
  188. "deprecated-typing-alias",
  189. "consider-using-alias",
  190. "consider-alternative-union-syntax",
  191. "broken-noreturn",
  192. "broken-collections-callable",
  193. )
  194. def visit_attribute(self, node: nodes.Attribute) -> None:
  195. if self._should_check_typing_alias and node.attrname in ALIAS_NAMES:
  196. self._check_for_typing_alias(node)
  197. if self._should_check_alternative_union_syntax and node.attrname in UNION_NAMES:
  198. self._check_for_alternative_union_syntax(node, node.attrname)
  199. if self._should_check_noreturn and node.attrname == "NoReturn":
  200. self._check_broken_noreturn(node)
  201. if self._should_check_callable and node.attrname == "Callable":
  202. self._check_broken_callable(node)
  203. @only_required_for_messages("redundant-typehint-argument")
  204. def visit_annassign(self, node: nodes.AnnAssign) -> None:
  205. annotation = node.annotation
  206. if self._is_deprecated_union_annotation(annotation, "Optional"):
  207. if self._is_optional_none_annotation(annotation):
  208. self.add_message(
  209. "redundant-typehint-argument",
  210. node=annotation,
  211. args="None",
  212. confidence=HIGH,
  213. )
  214. return
  215. if self._is_deprecated_union_annotation(annotation, "Union") and isinstance(
  216. annotation.slice, nodes.Tuple
  217. ):
  218. types = annotation.slice.elts
  219. elif self._is_binop_union_annotation(annotation):
  220. types = self._parse_binops_typehints(annotation)
  221. else:
  222. return
  223. self._check_union_types(types, node)
  224. @staticmethod
  225. def _is_deprecated_union_annotation(
  226. annotation: nodes.NodeNG, union_name: str
  227. ) -> bool:
  228. return (
  229. isinstance(annotation, nodes.Subscript)
  230. and isinstance(annotation.value, nodes.Name)
  231. and annotation.value.name == union_name
  232. )
  233. def _is_binop_union_annotation(self, annotation: nodes.NodeNG) -> bool:
  234. return self._should_check_alternative_union_syntax and isinstance(
  235. annotation, nodes.BinOp
  236. )
  237. @staticmethod
  238. def _is_optional_none_annotation(annotation: nodes.Subscript) -> bool:
  239. return (
  240. isinstance(annotation.slice, nodes.Const) and annotation.slice.value is None
  241. )
  242. def _parse_binops_typehints(
  243. self, binop_node: nodes.BinOp, typehints_list: list[nodes.NodeNG] | None = None
  244. ) -> list[nodes.NodeNG]:
  245. typehints_list = typehints_list or []
  246. if isinstance(binop_node.left, nodes.BinOp):
  247. typehints_list.extend(
  248. self._parse_binops_typehints(binop_node.left, typehints_list)
  249. )
  250. else:
  251. typehints_list.append(binop_node.left)
  252. typehints_list.append(binop_node.right)
  253. return typehints_list
  254. def _check_union_types(
  255. self, types: list[nodes.NodeNG], annotation: nodes.NodeNG
  256. ) -> None:
  257. types_set = set()
  258. for typehint in types:
  259. typehint_str = typehint.as_string()
  260. if typehint_str in types_set:
  261. self.add_message(
  262. "redundant-typehint-argument",
  263. node=annotation,
  264. args=(typehint_str),
  265. confidence=HIGH,
  266. )
  267. else:
  268. types_set.add(typehint_str)
  269. def _check_for_alternative_union_syntax(
  270. self,
  271. node: nodes.Name | nodes.Attribute,
  272. name: str,
  273. ) -> None:
  274. """Check if alternative union syntax could be used.
  275. Requires
  276. - Python 3.10
  277. - OR: Python 3.7+ with postponed evaluation in
  278. a type annotation context
  279. """
  280. inferred = safe_infer(node)
  281. if not (
  282. isinstance(inferred, nodes.FunctionDef)
  283. and inferred.qname() in {"typing.Optional", "typing.Union"}
  284. or isinstance(inferred, astroid.bases.Instance)
  285. and inferred.qname() == "typing._SpecialForm"
  286. ):
  287. return
  288. if not (self._py310_plus or is_node_in_type_annotation_context(node)):
  289. return
  290. self.add_message(
  291. "consider-alternative-union-syntax",
  292. node=node,
  293. args=(name, self._msg_postponed_eval_hint(node)),
  294. confidence=INFERENCE,
  295. )
  296. def _check_for_typing_alias(
  297. self,
  298. node: nodes.Name | nodes.Attribute,
  299. ) -> None:
  300. """Check if typing alias is deprecated or could be replaced.
  301. Requires
  302. - Python 3.9
  303. - OR: Python 3.7+ with postponed evaluation in
  304. a type annotation context
  305. For Python 3.7+: Only emit message if change doesn't create
  306. any name collisions, only ever used in a type annotation
  307. context, and can safely be replaced.
  308. """
  309. inferred = safe_infer(node)
  310. if not isinstance(inferred, nodes.ClassDef):
  311. return
  312. alias = DEPRECATED_TYPING_ALIASES.get(inferred.qname(), None)
  313. if alias is None:
  314. return
  315. if self._py39_plus:
  316. if inferred.qname() == "typing.Callable" and self._broken_callable_location(
  317. node
  318. ):
  319. self._found_broken_callable_location = True
  320. self._deprecated_typing_alias_msgs.append(
  321. DeprecatedTypingAliasMsg(
  322. node,
  323. inferred.qname(),
  324. alias.name,
  325. )
  326. )
  327. return
  328. # For PY37+, check for type annotation context first
  329. if not is_node_in_type_annotation_context(node) and isinstance(
  330. node.parent, nodes.Subscript
  331. ):
  332. if alias.name_collision is True:
  333. self._alias_name_collisions.add(inferred.qname())
  334. return
  335. self._consider_using_alias_msgs.append(
  336. DeprecatedTypingAliasMsg(
  337. node,
  338. inferred.qname(),
  339. alias.name,
  340. isinstance(node.parent, nodes.Subscript),
  341. )
  342. )
  343. @only_required_for_messages("consider-using-alias", "deprecated-typing-alias")
  344. def leave_module(self, node: nodes.Module) -> None:
  345. """After parsing of module is complete, add messages for
  346. 'consider-using-alias' check.
  347. Make sure results are safe to recommend / collision free.
  348. """
  349. if self._py39_plus:
  350. for msg in self._deprecated_typing_alias_msgs:
  351. if (
  352. self._found_broken_callable_location
  353. and msg.qname == "typing.Callable"
  354. ):
  355. continue
  356. self.add_message(
  357. "deprecated-typing-alias",
  358. node=msg.node,
  359. args=(msg.qname, msg.alias),
  360. confidence=INFERENCE,
  361. )
  362. elif self._py37_plus:
  363. msg_future_import = self._msg_postponed_eval_hint(node)
  364. for msg in self._consider_using_alias_msgs:
  365. if msg.qname in self._alias_name_collisions:
  366. continue
  367. self.add_message(
  368. "consider-using-alias",
  369. node=msg.node,
  370. args=(
  371. msg.qname,
  372. msg.alias,
  373. msg_future_import if msg.parent_subscript else "",
  374. ),
  375. confidence=INFERENCE,
  376. )
  377. # Clear all module cache variables
  378. self._found_broken_callable_location = False
  379. self._deprecated_typing_alias_msgs.clear()
  380. self._alias_name_collisions.clear()
  381. self._consider_using_alias_msgs.clear()
  382. def _check_broken_noreturn(self, node: nodes.Name | nodes.Attribute) -> None:
  383. """Check for 'NoReturn' inside compound types."""
  384. if not isinstance(node.parent, nodes.BaseContainer):
  385. # NoReturn not part of a Union or Callable type
  386. return
  387. if (
  388. in_type_checking_block(node)
  389. or is_postponed_evaluation_enabled(node)
  390. and is_node_in_type_annotation_context(node)
  391. ):
  392. return
  393. for inferred in node.infer():
  394. # To deal with typing_extensions, don't use safe_infer
  395. if (
  396. isinstance(inferred, (nodes.FunctionDef, nodes.ClassDef))
  397. and inferred.qname() in TYPING_NORETURN
  398. # In Python 3.7 - 3.8, NoReturn is alias of '_SpecialForm'
  399. or isinstance(inferred, astroid.bases.BaseInstance)
  400. and isinstance(inferred._proxied, nodes.ClassDef)
  401. and inferred._proxied.qname() == "typing._SpecialForm"
  402. ):
  403. self.add_message("broken-noreturn", node=node, confidence=INFERENCE)
  404. break
  405. def _check_broken_callable(self, node: nodes.Name | nodes.Attribute) -> None:
  406. """Check for 'collections.abc.Callable' inside Optional and Union."""
  407. inferred = safe_infer(node)
  408. if not (
  409. isinstance(inferred, nodes.ClassDef)
  410. and inferred.qname() == "_collections_abc.Callable"
  411. and self._broken_callable_location(node)
  412. ):
  413. return
  414. self.add_message("broken-collections-callable", node=node, confidence=INFERENCE)
  415. def _broken_callable_location(self, node: nodes.Name | nodes.Attribute) -> bool:
  416. """Check if node would be a broken location for collections.abc.Callable."""
  417. if (
  418. in_type_checking_block(node)
  419. or is_postponed_evaluation_enabled(node)
  420. and is_node_in_type_annotation_context(node)
  421. ):
  422. return False
  423. # Check first Callable arg is a list of arguments -> Callable[[int], None]
  424. if not (
  425. isinstance(node.parent, nodes.Subscript)
  426. and isinstance(node.parent.slice, nodes.Tuple)
  427. and len(node.parent.slice.elts) == 2
  428. and isinstance(node.parent.slice.elts[0], nodes.List)
  429. ):
  430. return False
  431. # Check nested inside Optional or Union
  432. parent_subscript = node.parent.parent
  433. if isinstance(parent_subscript, nodes.BaseContainer):
  434. parent_subscript = parent_subscript.parent
  435. if not (
  436. isinstance(parent_subscript, nodes.Subscript)
  437. and isinstance(parent_subscript.value, (nodes.Name, nodes.Attribute))
  438. ):
  439. return False
  440. inferred_parent = safe_infer(parent_subscript.value)
  441. if not (
  442. isinstance(inferred_parent, nodes.FunctionDef)
  443. and inferred_parent.qname() in {"typing.Optional", "typing.Union"}
  444. or isinstance(inferred_parent, astroid.bases.Instance)
  445. and inferred_parent.qname() == "typing._SpecialForm"
  446. ):
  447. return False
  448. return True
  449. def register(linter: PyLinter) -> None:
  450. linter.register_checker(TypingChecker(linter))