typing.py 22 KB

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