utils.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353
  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. """Some functions that may be useful for various checkers."""
  5. from __future__ import annotations
  6. import builtins
  7. import fnmatch
  8. import itertools
  9. import numbers
  10. import re
  11. import string
  12. import warnings
  13. from collections import deque
  14. from collections.abc import Iterable, Iterator
  15. from functools import lru_cache, partial
  16. from re import Match
  17. from typing import TYPE_CHECKING, Any, Callable, TypeVar
  18. import _string
  19. import astroid.objects
  20. from astroid import TooManyLevelsError, nodes, util
  21. from astroid.context import InferenceContext
  22. from astroid.exceptions import AstroidError
  23. from astroid.nodes._base_nodes import ImportNode
  24. from astroid.typing import InferenceResult, SuccessfulInferenceResult
  25. if TYPE_CHECKING:
  26. from functools import _lru_cache_wrapper
  27. from pylint.checkers import BaseChecker
  28. _NodeT = TypeVar("_NodeT", bound=nodes.NodeNG)
  29. _CheckerT = TypeVar("_CheckerT", bound="BaseChecker")
  30. AstCallbackMethod = Callable[[_CheckerT, _NodeT], None]
  31. COMP_NODE_TYPES = (
  32. nodes.ListComp,
  33. nodes.SetComp,
  34. nodes.DictComp,
  35. nodes.GeneratorExp,
  36. )
  37. EXCEPTIONS_MODULE = "builtins"
  38. ABC_MODULES = {"abc", "_py_abc"}
  39. ABC_METHODS = {
  40. "abc.abstractproperty",
  41. "abc.abstractmethod",
  42. "abc.abstractclassmethod",
  43. "abc.abstractstaticmethod",
  44. }
  45. TYPING_PROTOCOLS = frozenset(
  46. {"typing.Protocol", "typing_extensions.Protocol", ".Protocol"}
  47. )
  48. COMMUTATIVE_OPERATORS = frozenset({"*", "+", "^", "&", "|"})
  49. ITER_METHOD = "__iter__"
  50. AITER_METHOD = "__aiter__"
  51. NEXT_METHOD = "__next__"
  52. GETITEM_METHOD = "__getitem__"
  53. CLASS_GETITEM_METHOD = "__class_getitem__"
  54. SETITEM_METHOD = "__setitem__"
  55. DELITEM_METHOD = "__delitem__"
  56. CONTAINS_METHOD = "__contains__"
  57. KEYS_METHOD = "keys"
  58. # Dictionary which maps the number of expected parameters a
  59. # special method can have to a set of special methods.
  60. # The following keys are used to denote the parameters restrictions:
  61. #
  62. # * None: variable number of parameters
  63. # * number: exactly that number of parameters
  64. # * tuple: these are the odd ones. Basically it means that the function
  65. # can work with any number of arguments from that tuple,
  66. # although it's best to implement it in order to accept
  67. # all of them.
  68. _SPECIAL_METHODS_PARAMS = {
  69. None: ("__new__", "__init__", "__call__", "__init_subclass__"),
  70. 0: (
  71. "__del__",
  72. "__repr__",
  73. "__str__",
  74. "__bytes__",
  75. "__hash__",
  76. "__bool__",
  77. "__dir__",
  78. "__len__",
  79. "__length_hint__",
  80. "__iter__",
  81. "__reversed__",
  82. "__neg__",
  83. "__pos__",
  84. "__abs__",
  85. "__invert__",
  86. "__complex__",
  87. "__int__",
  88. "__float__",
  89. "__index__",
  90. "__trunc__",
  91. "__floor__",
  92. "__ceil__",
  93. "__enter__",
  94. "__aenter__",
  95. "__getnewargs_ex__",
  96. "__getnewargs__",
  97. "__getstate__",
  98. "__reduce__",
  99. "__copy__",
  100. "__unicode__",
  101. "__nonzero__",
  102. "__await__",
  103. "__aiter__",
  104. "__anext__",
  105. "__fspath__",
  106. "__subclasses__",
  107. ),
  108. 1: (
  109. "__format__",
  110. "__lt__",
  111. "__le__",
  112. "__eq__",
  113. "__ne__",
  114. "__gt__",
  115. "__ge__",
  116. "__getattr__",
  117. "__getattribute__",
  118. "__delattr__",
  119. "__delete__",
  120. "__instancecheck__",
  121. "__subclasscheck__",
  122. "__getitem__",
  123. "__missing__",
  124. "__delitem__",
  125. "__contains__",
  126. "__add__",
  127. "__sub__",
  128. "__mul__",
  129. "__truediv__",
  130. "__floordiv__",
  131. "__rfloordiv__",
  132. "__mod__",
  133. "__divmod__",
  134. "__lshift__",
  135. "__rshift__",
  136. "__and__",
  137. "__xor__",
  138. "__or__",
  139. "__radd__",
  140. "__rsub__",
  141. "__rmul__",
  142. "__rtruediv__",
  143. "__rmod__",
  144. "__rdivmod__",
  145. "__rpow__",
  146. "__rlshift__",
  147. "__rrshift__",
  148. "__rand__",
  149. "__rxor__",
  150. "__ror__",
  151. "__iadd__",
  152. "__isub__",
  153. "__imul__",
  154. "__itruediv__",
  155. "__ifloordiv__",
  156. "__imod__",
  157. "__ilshift__",
  158. "__irshift__",
  159. "__iand__",
  160. "__ixor__",
  161. "__ior__",
  162. "__ipow__",
  163. "__setstate__",
  164. "__reduce_ex__",
  165. "__deepcopy__",
  166. "__cmp__",
  167. "__matmul__",
  168. "__rmatmul__",
  169. "__imatmul__",
  170. "__div__",
  171. ),
  172. 2: ("__setattr__", "__get__", "__set__", "__setitem__", "__set_name__"),
  173. 3: ("__exit__", "__aexit__"),
  174. (0, 1): ("__round__",),
  175. (1, 2): ("__pow__",),
  176. }
  177. SPECIAL_METHODS_PARAMS = {
  178. name: params
  179. for params, methods in _SPECIAL_METHODS_PARAMS.items()
  180. for name in methods
  181. }
  182. PYMETHODS = set(SPECIAL_METHODS_PARAMS)
  183. SUBSCRIPTABLE_CLASSES_PEP585 = frozenset(
  184. (
  185. "builtins.tuple",
  186. "builtins.list",
  187. "builtins.dict",
  188. "builtins.set",
  189. "builtins.frozenset",
  190. "builtins.type",
  191. "collections.deque",
  192. "collections.defaultdict",
  193. "collections.OrderedDict",
  194. "collections.Counter",
  195. "collections.ChainMap",
  196. "_collections_abc.Awaitable",
  197. "_collections_abc.Coroutine",
  198. "_collections_abc.AsyncIterable",
  199. "_collections_abc.AsyncIterator",
  200. "_collections_abc.AsyncGenerator",
  201. "_collections_abc.Iterable",
  202. "_collections_abc.Iterator",
  203. "_collections_abc.Generator",
  204. "_collections_abc.Reversible",
  205. "_collections_abc.Container",
  206. "_collections_abc.Collection",
  207. "_collections_abc.Callable",
  208. "_collections_abc.Set",
  209. "_collections_abc.MutableSet",
  210. "_collections_abc.Mapping",
  211. "_collections_abc.MutableMapping",
  212. "_collections_abc.Sequence",
  213. "_collections_abc.MutableSequence",
  214. "_collections_abc.ByteString",
  215. "_collections_abc.MappingView",
  216. "_collections_abc.KeysView",
  217. "_collections_abc.ItemsView",
  218. "_collections_abc.ValuesView",
  219. "contextlib.AbstractContextManager",
  220. "contextlib.AbstractAsyncContextManager",
  221. "re.Pattern",
  222. "re.Match",
  223. )
  224. )
  225. SINGLETON_VALUES = {True, False, None}
  226. TERMINATING_FUNCS_QNAMES = frozenset(
  227. {"_sitebuiltins.Quitter", "sys.exit", "posix._exit", "nt._exit"}
  228. )
  229. class NoSuchArgumentError(Exception):
  230. pass
  231. class InferredTypeError(Exception):
  232. pass
  233. def is_inside_lambda(node: nodes.NodeNG) -> bool:
  234. """Return whether the given node is inside a lambda."""
  235. warnings.warn(
  236. "utils.is_inside_lambda will be removed in favour of calling "
  237. "utils.get_node_first_ancestor_of_type(x, nodes.Lambda) in pylint 3.0",
  238. DeprecationWarning,
  239. stacklevel=2,
  240. )
  241. return any(isinstance(parent, nodes.Lambda) for parent in node.node_ancestors())
  242. def get_all_elements(
  243. node: nodes.NodeNG,
  244. ) -> Iterable[nodes.NodeNG]:
  245. """Recursively returns all atoms in nested lists and tuples."""
  246. if isinstance(node, (nodes.Tuple, nodes.List)):
  247. for child in node.elts:
  248. yield from get_all_elements(child)
  249. else:
  250. yield node
  251. def is_super(node: nodes.NodeNG) -> bool:
  252. """Return True if the node is referencing the "super" builtin function."""
  253. if getattr(node, "name", None) == "super" and node.root().name == "builtins":
  254. return True
  255. return False
  256. def is_error(node: nodes.FunctionDef) -> bool:
  257. """Return true if the given function node only raises an exception."""
  258. return len(node.body) == 1 and isinstance(node.body[0], nodes.Raise)
  259. builtins = builtins.__dict__.copy() # type: ignore[assignment]
  260. SPECIAL_BUILTINS = ("__builtins__",) # '__path__', '__file__')
  261. def is_builtin_object(node: nodes.NodeNG) -> bool:
  262. """Returns True if the given node is an object from the __builtin__ module."""
  263. return node and node.root().name == "builtins" # type: ignore[no-any-return]
  264. def is_builtin(name: str) -> bool:
  265. """Return true if <name> could be considered as a builtin defined by python."""
  266. return name in builtins or name in SPECIAL_BUILTINS # type: ignore[operator]
  267. def is_defined_in_scope(
  268. var_node: nodes.NodeNG,
  269. varname: str,
  270. scope: nodes.NodeNG,
  271. ) -> bool:
  272. return defnode_in_scope(var_node, varname, scope) is not None
  273. # pylint: disable = too-many-branches
  274. def defnode_in_scope(
  275. var_node: nodes.NodeNG,
  276. varname: str,
  277. scope: nodes.NodeNG,
  278. ) -> nodes.NodeNG | None:
  279. if isinstance(scope, nodes.If):
  280. for node in scope.body:
  281. if isinstance(node, nodes.Nonlocal) and varname in node.names:
  282. return node
  283. if isinstance(node, nodes.Assign):
  284. for target in node.targets:
  285. if isinstance(target, nodes.AssignName) and target.name == varname:
  286. return target
  287. elif isinstance(scope, (COMP_NODE_TYPES, nodes.For)):
  288. for ass_node in scope.nodes_of_class(nodes.AssignName):
  289. if ass_node.name == varname:
  290. return ass_node
  291. elif isinstance(scope, nodes.With):
  292. for expr, ids in scope.items:
  293. if expr.parent_of(var_node):
  294. break
  295. if ids and isinstance(ids, nodes.AssignName) and ids.name == varname:
  296. return ids
  297. elif isinstance(scope, (nodes.Lambda, nodes.FunctionDef)):
  298. if scope.args.is_argument(varname):
  299. # If the name is found inside a default value
  300. # of a function, then let the search continue
  301. # in the parent's tree.
  302. if scope.args.parent_of(var_node):
  303. try:
  304. scope.args.default_value(varname)
  305. scope = scope.parent
  306. defnode = defnode_in_scope(var_node, varname, scope)
  307. except astroid.NoDefault:
  308. pass
  309. else:
  310. return defnode
  311. return scope
  312. if getattr(scope, "name", None) == varname:
  313. return scope
  314. elif isinstance(scope, nodes.ExceptHandler):
  315. if isinstance(scope.name, nodes.AssignName):
  316. ass_node = scope.name
  317. if ass_node.name == varname:
  318. return ass_node
  319. return None
  320. def is_defined_before(var_node: nodes.Name) -> bool:
  321. """Check if the given variable node is defined before.
  322. Verify that the variable node is defined by a parent node
  323. (e.g. if or with) earlier than `var_node`, or is defined by a
  324. (list, set, dict, or generator comprehension, lambda)
  325. or in a previous sibling node on the same line
  326. (statement_defining ; statement_using).
  327. """
  328. varname = var_node.name
  329. for parent in var_node.node_ancestors():
  330. defnode = defnode_in_scope(var_node, varname, parent)
  331. if defnode is None:
  332. continue
  333. defnode_scope = defnode.scope()
  334. if isinstance(defnode_scope, COMP_NODE_TYPES + (nodes.Lambda,)):
  335. # Avoid the case where var_node_scope is a nested function
  336. # FunctionDef is a Lambda until https://github.com/pylint-dev/astroid/issues/291
  337. if isinstance(defnode_scope, nodes.FunctionDef):
  338. var_node_scope = var_node.scope()
  339. if var_node_scope is not defnode_scope and isinstance(
  340. var_node_scope, nodes.FunctionDef
  341. ):
  342. return False
  343. return True
  344. if defnode.lineno < var_node.lineno:
  345. return True
  346. # `defnode` and `var_node` on the same line
  347. for defnode_anc in defnode.node_ancestors():
  348. if defnode_anc.lineno != var_node.lineno:
  349. continue
  350. if isinstance(
  351. defnode_anc,
  352. (
  353. nodes.For,
  354. nodes.While,
  355. nodes.With,
  356. nodes.TryExcept,
  357. nodes.TryFinally,
  358. nodes.ExceptHandler,
  359. ),
  360. ):
  361. return True
  362. # possibly multiple statements on the same line using semicolon separator
  363. stmt = var_node.statement(future=True)
  364. _node = stmt.previous_sibling()
  365. lineno = stmt.fromlineno
  366. while _node and _node.fromlineno == lineno:
  367. for assign_node in _node.nodes_of_class(nodes.AssignName):
  368. if assign_node.name == varname:
  369. return True
  370. for imp_node in _node.nodes_of_class((nodes.ImportFrom, nodes.Import)):
  371. if varname in [name[1] or name[0] for name in imp_node.names]:
  372. return True
  373. _node = _node.previous_sibling()
  374. return False
  375. def is_default_argument(node: nodes.NodeNG, scope: nodes.NodeNG | None = None) -> bool:
  376. """Return true if the given Name node is used in function or lambda
  377. default argument's value.
  378. """
  379. if not scope:
  380. scope = node.scope()
  381. if isinstance(scope, (nodes.FunctionDef, nodes.Lambda)):
  382. all_defaults = itertools.chain(
  383. scope.args.defaults, (d for d in scope.args.kw_defaults if d is not None)
  384. )
  385. return any(
  386. default_name_node is node
  387. for default_node in all_defaults
  388. for default_name_node in default_node.nodes_of_class(nodes.Name)
  389. )
  390. return False
  391. def is_func_decorator(node: nodes.NodeNG) -> bool:
  392. """Return true if the name is used in function decorator."""
  393. for parent in node.node_ancestors():
  394. if isinstance(parent, nodes.Decorators):
  395. return True
  396. if parent.is_statement or isinstance(
  397. parent,
  398. (
  399. nodes.Lambda,
  400. nodes.ComprehensionScope,
  401. nodes.ListComp,
  402. ),
  403. ):
  404. break
  405. return False
  406. def is_ancestor_name(frame: nodes.ClassDef, node: nodes.NodeNG) -> bool:
  407. """Return whether `frame` is an astroid.Class node with `node` in the
  408. subtree of its bases attribute.
  409. """
  410. if not isinstance(frame, nodes.ClassDef):
  411. return False
  412. return any(node in base.nodes_of_class(nodes.Name) for base in frame.bases)
  413. def is_being_called(node: nodes.NodeNG) -> bool:
  414. """Return True if node is the function being called in a Call node."""
  415. return isinstance(node.parent, nodes.Call) and node.parent.func is node
  416. def assign_parent(node: nodes.NodeNG) -> nodes.NodeNG:
  417. """Return the higher parent which is not an AssignName, Tuple or List node."""
  418. while node and isinstance(node, (nodes.AssignName, nodes.Tuple, nodes.List)):
  419. node = node.parent
  420. return node
  421. def overrides_a_method(class_node: nodes.ClassDef, name: str) -> bool:
  422. """Return True if <name> is a method overridden from an ancestor
  423. which is not the base object class.
  424. """
  425. for ancestor in class_node.ancestors():
  426. if ancestor.name == "object":
  427. continue
  428. if name in ancestor and isinstance(ancestor[name], nodes.FunctionDef):
  429. return True
  430. return False
  431. def only_required_for_messages(
  432. *messages: str,
  433. ) -> Callable[
  434. [AstCallbackMethod[_CheckerT, _NodeT]], AstCallbackMethod[_CheckerT, _NodeT]
  435. ]:
  436. """Decorator to store messages that are handled by a checker method as an
  437. attribute of the function object.
  438. This information is used by ``ASTWalker`` to decide whether to call the decorated
  439. method or not. If none of the messages is enabled, the method will be skipped.
  440. Therefore, the list of messages must be well maintained at all times!
  441. This decorator only has an effect on ``visit_*`` and ``leave_*`` methods
  442. of a class inheriting from ``BaseChecker``.
  443. """
  444. def store_messages(
  445. func: AstCallbackMethod[_CheckerT, _NodeT]
  446. ) -> AstCallbackMethod[_CheckerT, _NodeT]:
  447. func.checks_msgs = messages # type: ignore[attr-defined]
  448. return func
  449. return store_messages
  450. def check_messages(
  451. *messages: str,
  452. ) -> Callable[
  453. [AstCallbackMethod[_CheckerT, _NodeT]], AstCallbackMethod[_CheckerT, _NodeT]
  454. ]:
  455. """Kept for backwards compatibility, deprecated.
  456. Use only_required_for_messages instead, which conveys the intent of the decorator much clearer.
  457. """
  458. warnings.warn(
  459. "utils.check_messages will be removed in favour of calling "
  460. "utils.only_required_for_messages in pylint 3.0",
  461. DeprecationWarning,
  462. stacklevel=2,
  463. )
  464. return only_required_for_messages(*messages)
  465. class IncompleteFormatString(Exception):
  466. """A format string ended in the middle of a format specifier."""
  467. class UnsupportedFormatCharacter(Exception):
  468. """A format character in a format string is not one of the supported
  469. format characters.
  470. """
  471. def __init__(self, index: int) -> None:
  472. super().__init__(index)
  473. self.index = index
  474. def parse_format_string(
  475. format_string: str,
  476. ) -> tuple[set[str], int, dict[str, str], list[str]]:
  477. """Parses a format string, returning a tuple (keys, num_args).
  478. Where 'keys' is the set of mapping keys in the format string, and 'num_args' is the number
  479. of arguments required by the format string. Raises IncompleteFormatString or
  480. UnsupportedFormatCharacter if a parse error occurs.
  481. """
  482. keys = set()
  483. key_types = {}
  484. pos_types = []
  485. num_args = 0
  486. def next_char(i: int) -> tuple[int, str]:
  487. i += 1
  488. if i == len(format_string):
  489. raise IncompleteFormatString
  490. return (i, format_string[i])
  491. i = 0
  492. while i < len(format_string):
  493. char = format_string[i]
  494. if char == "%":
  495. i, char = next_char(i)
  496. # Parse the mapping key (optional).
  497. key = None
  498. if char == "(":
  499. depth = 1
  500. i, char = next_char(i)
  501. key_start = i
  502. while depth != 0:
  503. if char == "(":
  504. depth += 1
  505. elif char == ")":
  506. depth -= 1
  507. i, char = next_char(i)
  508. key_end = i - 1
  509. key = format_string[key_start:key_end]
  510. # Parse the conversion flags (optional).
  511. while char in "#0- +":
  512. i, char = next_char(i)
  513. # Parse the minimum field width (optional).
  514. if char == "*":
  515. num_args += 1
  516. i, char = next_char(i)
  517. else:
  518. while char in string.digits:
  519. i, char = next_char(i)
  520. # Parse the precision (optional).
  521. if char == ".":
  522. i, char = next_char(i)
  523. if char == "*":
  524. num_args += 1
  525. i, char = next_char(i)
  526. else:
  527. while char in string.digits:
  528. i, char = next_char(i)
  529. # Parse the length modifier (optional).
  530. if char in "hlL":
  531. i, char = next_char(i)
  532. # Parse the conversion type (mandatory).
  533. flags = "diouxXeEfFgGcrs%a"
  534. if char not in flags:
  535. raise UnsupportedFormatCharacter(i)
  536. if key:
  537. keys.add(key)
  538. key_types[key] = char
  539. elif char != "%":
  540. num_args += 1
  541. pos_types.append(char)
  542. i += 1
  543. return keys, num_args, key_types, pos_types
  544. def split_format_field_names(
  545. format_string: str,
  546. ) -> tuple[str, Iterable[tuple[bool, str]]]:
  547. try:
  548. return _string.formatter_field_name_split(format_string) # type: ignore[no-any-return]
  549. except ValueError as e:
  550. raise IncompleteFormatString() from e
  551. def collect_string_fields(format_string: str) -> Iterable[str | None]:
  552. """Given a format string, return an iterator
  553. of all the valid format fields.
  554. It handles nested fields as well.
  555. """
  556. formatter = string.Formatter()
  557. # pylint: disable = too-many-try-statements
  558. try:
  559. parseiterator = formatter.parse(format_string)
  560. for result in parseiterator:
  561. if all(item is None for item in result[1:]):
  562. # not a replacement format
  563. continue
  564. name = result[1]
  565. nested = result[2]
  566. yield name
  567. if nested:
  568. yield from collect_string_fields(nested)
  569. except ValueError as exc:
  570. # Probably the format string is invalid.
  571. if exc.args[0].startswith("cannot switch from manual"):
  572. # On Jython, parsing a string with both manual
  573. # and automatic positions will fail with a ValueError,
  574. # while on CPython it will simply return the fields,
  575. # the validation being done in the interpreter (?).
  576. # We're just returning two mixed fields in order
  577. # to trigger the format-combined-specification check.
  578. yield ""
  579. yield "1"
  580. return
  581. raise IncompleteFormatString(format_string) from exc
  582. def parse_format_method_string(
  583. format_string: str,
  584. ) -> tuple[list[tuple[str, list[tuple[bool, str]]]], int, int]:
  585. """Parses a PEP 3101 format string, returning a tuple of
  586. (keyword_arguments, implicit_pos_args_cnt, explicit_pos_args).
  587. keyword_arguments is the set of mapping keys in the format string, implicit_pos_args_cnt
  588. is the number of arguments required by the format string and
  589. explicit_pos_args is the number of arguments passed with the position.
  590. """
  591. keyword_arguments = []
  592. implicit_pos_args_cnt = 0
  593. explicit_pos_args = set()
  594. for name in collect_string_fields(format_string):
  595. if name and str(name).isdigit():
  596. explicit_pos_args.add(str(name))
  597. elif name:
  598. keyname, fielditerator = split_format_field_names(name)
  599. if isinstance(keyname, numbers.Number):
  600. explicit_pos_args.add(str(keyname))
  601. try:
  602. keyword_arguments.append((keyname, list(fielditerator)))
  603. except ValueError as e:
  604. raise IncompleteFormatString() from e
  605. else:
  606. implicit_pos_args_cnt += 1
  607. return keyword_arguments, implicit_pos_args_cnt, len(explicit_pos_args)
  608. def is_attr_protected(attrname: str) -> bool:
  609. """Return True if attribute name is protected (start with _ and some other
  610. details), False otherwise.
  611. """
  612. return (
  613. attrname[0] == "_"
  614. and attrname != "_"
  615. and not (attrname.startswith("__") and attrname.endswith("__"))
  616. )
  617. def node_frame_class(node: nodes.NodeNG) -> nodes.ClassDef | None:
  618. """Return the class that is wrapping the given node.
  619. The function returns a class for a method node (or a staticmethod or a
  620. classmethod), otherwise it returns `None`.
  621. """
  622. klass = node.frame(future=True)
  623. nodes_to_check = (
  624. nodes.NodeNG,
  625. astroid.UnboundMethod,
  626. astroid.BaseInstance,
  627. )
  628. while (
  629. klass
  630. and isinstance(klass, nodes_to_check)
  631. and not isinstance(klass, nodes.ClassDef)
  632. ):
  633. if klass.parent is None:
  634. return None
  635. klass = klass.parent.frame(future=True)
  636. return klass
  637. def get_outer_class(class_node: astroid.ClassDef) -> astroid.ClassDef | None:
  638. """Return the class that is the outer class of given (nested) class_node."""
  639. parent_klass = class_node.parent.frame(future=True)
  640. return parent_klass if isinstance(parent_klass, astroid.ClassDef) else None
  641. def is_attr_private(attrname: str) -> Match[str] | None:
  642. """Check that attribute name is private (at least two leading underscores,
  643. at most one trailing underscore).
  644. """
  645. regex = re.compile("^_{2,10}.*[^_]+_?$")
  646. return regex.match(attrname)
  647. def get_argument_from_call(
  648. call_node: nodes.Call, position: int | None = None, keyword: str | None = None
  649. ) -> nodes.Name:
  650. """Returns the specified argument from a function call.
  651. :param nodes.Call call_node: Node representing a function call to check.
  652. :param int position: position of the argument.
  653. :param str keyword: the keyword of the argument.
  654. :returns: The node representing the argument, None if the argument is not found.
  655. :rtype: nodes.Name
  656. :raises ValueError: if both position and keyword are None.
  657. :raises NoSuchArgumentError: if no argument at the provided position or with
  658. the provided keyword.
  659. """
  660. if position is None and keyword is None:
  661. raise ValueError("Must specify at least one of: position or keyword.")
  662. if position is not None:
  663. try:
  664. return call_node.args[position]
  665. except IndexError:
  666. pass
  667. if keyword and call_node.keywords:
  668. for arg in call_node.keywords:
  669. if arg.arg == keyword:
  670. return arg.value
  671. raise NoSuchArgumentError
  672. def infer_kwarg_from_call(call_node: nodes.Call, keyword: str) -> nodes.Name | None:
  673. """Returns the specified argument from a function's kwargs.
  674. :param nodes.Call call_node: Node representing a function call to check.
  675. :param str keyword: Name of the argument to be extracted.
  676. :returns: The node representing the argument, None if the argument is not found.
  677. :rtype: nodes.Name
  678. """
  679. for arg in call_node.kwargs:
  680. inferred = safe_infer(arg.value)
  681. if isinstance(inferred, nodes.Dict):
  682. for item in inferred.items:
  683. if item[0].value == keyword:
  684. return item[1]
  685. return None
  686. def inherit_from_std_ex(node: nodes.NodeNG | astroid.Instance) -> bool:
  687. """Return whether the given class node is subclass of
  688. exceptions.Exception.
  689. """
  690. ancestors = node.ancestors() if hasattr(node, "ancestors") else []
  691. return any(
  692. ancestor.name in {"Exception", "BaseException"}
  693. and ancestor.root().name == EXCEPTIONS_MODULE
  694. for ancestor in itertools.chain([node], ancestors)
  695. )
  696. def error_of_type(
  697. handler: nodes.ExceptHandler,
  698. error_type: str | type[Exception] | tuple[str | type[Exception], ...],
  699. ) -> bool:
  700. """Check if the given exception handler catches
  701. the given error_type.
  702. The *handler* parameter is a node, representing an ExceptHandler node.
  703. The *error_type* can be an exception, such as AttributeError,
  704. the name of an exception, or it can be a tuple of errors.
  705. The function will return True if the handler catches any of the
  706. given errors.
  707. """
  708. def stringify_error(error: str | type[Exception]) -> str:
  709. if not isinstance(error, str):
  710. return error.__name__
  711. return error
  712. if not isinstance(error_type, tuple):
  713. error_type = (error_type,)
  714. expected_errors = {stringify_error(error) for error in error_type}
  715. if not handler.type:
  716. return False
  717. return handler.catch(expected_errors) # type: ignore[no-any-return]
  718. def decorated_with_property(node: nodes.FunctionDef) -> bool:
  719. """Detect if the given function node is decorated with a property."""
  720. if not node.decorators:
  721. return False
  722. for decorator in node.decorators.nodes:
  723. try:
  724. if _is_property_decorator(decorator):
  725. return True
  726. except astroid.InferenceError:
  727. pass
  728. return False
  729. def _is_property_kind(node: nodes.NodeNG, *kinds: str) -> bool:
  730. if not isinstance(node, (astroid.UnboundMethod, nodes.FunctionDef)):
  731. return False
  732. if node.decorators:
  733. for decorator in node.decorators.nodes:
  734. if isinstance(decorator, nodes.Attribute) and decorator.attrname in kinds:
  735. return True
  736. return False
  737. def is_property_setter(node: nodes.NodeNG) -> bool:
  738. """Check if the given node is a property setter."""
  739. return _is_property_kind(node, "setter")
  740. def is_property_deleter(node: nodes.NodeNG) -> bool:
  741. """Check if the given node is a property deleter."""
  742. return _is_property_kind(node, "deleter")
  743. def is_property_setter_or_deleter(node: nodes.NodeNG) -> bool:
  744. """Check if the given node is either a property setter or a deleter."""
  745. return _is_property_kind(node, "setter", "deleter")
  746. def _is_property_decorator(decorator: nodes.Name) -> bool:
  747. for inferred in decorator.infer():
  748. if isinstance(inferred, nodes.ClassDef):
  749. if inferred.qname() in {"builtins.property", "functools.cached_property"}:
  750. return True
  751. for ancestor in inferred.ancestors():
  752. if ancestor.name == "property" and ancestor.root().name == "builtins":
  753. return True
  754. elif isinstance(inferred, nodes.FunctionDef):
  755. # If decorator is function, check if it has exactly one return
  756. # and the return is itself a function decorated with property
  757. returns: list[nodes.Return] = list(
  758. inferred._get_return_nodes_skip_functions()
  759. )
  760. if len(returns) == 1 and isinstance(
  761. returns[0].value, (nodes.Name, nodes.Attribute)
  762. ):
  763. inferred = safe_infer(returns[0].value)
  764. if (
  765. inferred
  766. and isinstance(inferred, astroid.objects.Property)
  767. and isinstance(inferred.function, nodes.FunctionDef)
  768. ):
  769. return decorated_with_property(inferred.function)
  770. return False
  771. def decorated_with(
  772. func: (
  773. nodes.ClassDef | nodes.FunctionDef | astroid.BoundMethod | astroid.UnboundMethod
  774. ),
  775. qnames: Iterable[str],
  776. ) -> bool:
  777. """Determine if the `func` node has a decorator with the qualified name `qname`."""
  778. decorators = func.decorators.nodes if func.decorators else []
  779. for decorator_node in decorators:
  780. if isinstance(decorator_node, nodes.Call):
  781. # We only want to infer the function name
  782. decorator_node = decorator_node.func
  783. try:
  784. if any(
  785. i.name in qnames or i.qname() in qnames
  786. for i in decorator_node.infer()
  787. if i is not None and not isinstance(i, util.UninferableBase)
  788. ):
  789. return True
  790. except astroid.InferenceError:
  791. continue
  792. return False
  793. def uninferable_final_decorators(
  794. node: nodes.Decorators,
  795. ) -> list[nodes.Attribute | nodes.Name | None]:
  796. """Return a list of uninferable `typing.final` decorators in `node`.
  797. This function is used to determine if the `typing.final` decorator is used
  798. with an unsupported Python version; the decorator cannot be inferred when
  799. using a Python version lower than 3.8.
  800. """
  801. decorators = []
  802. for decorator in getattr(node, "nodes", []):
  803. import_nodes: tuple[nodes.Import | nodes.ImportFrom] | None = None
  804. # Get the `Import` node. The decorator is of the form: @module.name
  805. if isinstance(decorator, nodes.Attribute):
  806. inferred = safe_infer(decorator.expr)
  807. if isinstance(inferred, nodes.Module) and inferred.qname() == "typing":
  808. _, import_nodes = decorator.expr.lookup(decorator.expr.name)
  809. # Get the `ImportFrom` node. The decorator is of the form: @name
  810. elif isinstance(decorator, nodes.Name):
  811. _, import_nodes = decorator.lookup(decorator.name)
  812. # The `final` decorator is expected to be found in the
  813. # import_nodes. Continue if we don't find any `Import` or `ImportFrom`
  814. # nodes for this decorator.
  815. if not import_nodes:
  816. continue
  817. import_node = import_nodes[0]
  818. if not isinstance(import_node, (astroid.Import, astroid.ImportFrom)):
  819. continue
  820. import_names = dict(import_node.names)
  821. # Check if the import is of the form: `from typing import final`
  822. is_from_import = ("final" in import_names) and import_node.modname == "typing"
  823. # Check if the import is of the form: `import typing`
  824. is_import = ("typing" in import_names) and getattr(
  825. decorator, "attrname", None
  826. ) == "final"
  827. if is_from_import or is_import:
  828. inferred = safe_infer(decorator)
  829. if inferred is None or isinstance(inferred, util.UninferableBase):
  830. decorators.append(decorator)
  831. return decorators
  832. @lru_cache(maxsize=1024)
  833. def unimplemented_abstract_methods(
  834. node: nodes.ClassDef, is_abstract_cb: nodes.FunctionDef = None
  835. ) -> dict[str, nodes.FunctionDef]:
  836. """Get the unimplemented abstract methods for the given *node*.
  837. A method can be considered abstract if the callback *is_abstract_cb*
  838. returns a ``True`` value. The check defaults to verifying that
  839. a method is decorated with abstract methods.
  840. It will return a dictionary of abstract method
  841. names and their inferred objects.
  842. """
  843. if is_abstract_cb is None:
  844. is_abstract_cb = partial(decorated_with, qnames=ABC_METHODS)
  845. visited: dict[str, nodes.FunctionDef] = {}
  846. try:
  847. mro = reversed(node.mro())
  848. except astroid.ResolveError:
  849. # Probably inconsistent hierarchy, don't try to figure this out here.
  850. return {}
  851. for ancestor in mro:
  852. for obj in ancestor.values():
  853. inferred = obj
  854. if isinstance(obj, nodes.AssignName):
  855. inferred = safe_infer(obj)
  856. if not inferred:
  857. # Might be an abstract function,
  858. # but since we don't have enough information
  859. # in order to take this decision, we're taking
  860. # the *safe* decision instead.
  861. if obj.name in visited:
  862. del visited[obj.name]
  863. continue
  864. if not isinstance(inferred, nodes.FunctionDef):
  865. if obj.name in visited:
  866. del visited[obj.name]
  867. if isinstance(inferred, nodes.FunctionDef):
  868. # It's critical to use the original name,
  869. # since after inferring, an object can be something
  870. # else than expected, as in the case of the
  871. # following assignment.
  872. #
  873. # class A:
  874. # def keys(self): pass
  875. # __iter__ = keys
  876. abstract = is_abstract_cb(inferred)
  877. if abstract:
  878. visited[obj.name] = inferred
  879. elif not abstract and obj.name in visited:
  880. del visited[obj.name]
  881. return visited
  882. def find_try_except_wrapper_node(
  883. node: nodes.NodeNG,
  884. ) -> nodes.ExceptHandler | nodes.TryExcept | None:
  885. """Return the ExceptHandler or the TryExcept node in which the node is."""
  886. current = node
  887. ignores = (nodes.ExceptHandler, nodes.TryExcept)
  888. while current and not isinstance(current.parent, ignores):
  889. current = current.parent
  890. if current and isinstance(current.parent, ignores):
  891. return current.parent
  892. return None
  893. def find_except_wrapper_node_in_scope(
  894. node: nodes.NodeNG,
  895. ) -> nodes.ExceptHandler | nodes.TryExcept | None:
  896. """Return the ExceptHandler in which the node is, without going out of scope."""
  897. for current in node.node_ancestors():
  898. if isinstance(current, astroid.scoped_nodes.LocalsDictNodeNG):
  899. # If we're inside a function/class definition, we don't want to keep checking
  900. # higher ancestors for `except` clauses, because if these exist, it means our
  901. # function/class was defined in an `except` clause, rather than the current code
  902. # actually running in an `except` clause.
  903. return None
  904. if isinstance(current, nodes.ExceptHandler):
  905. return current
  906. return None
  907. def is_from_fallback_block(node: nodes.NodeNG) -> bool:
  908. """Check if the given node is from a fallback import block."""
  909. context = find_try_except_wrapper_node(node)
  910. if not context:
  911. return False
  912. if isinstance(context, nodes.ExceptHandler):
  913. other_body = context.parent.body
  914. handlers = context.parent.handlers
  915. else:
  916. other_body = itertools.chain.from_iterable(
  917. handler.body for handler in context.handlers
  918. )
  919. handlers = context.handlers
  920. has_fallback_imports = any(
  921. isinstance(import_node, (nodes.ImportFrom, nodes.Import))
  922. for import_node in other_body
  923. )
  924. ignores_import_error = _except_handlers_ignores_exceptions(
  925. handlers, (ImportError, ModuleNotFoundError)
  926. )
  927. return ignores_import_error or has_fallback_imports
  928. def _except_handlers_ignores_exceptions(
  929. handlers: nodes.ExceptHandler,
  930. exceptions: tuple[type[ImportError], type[ModuleNotFoundError]],
  931. ) -> bool:
  932. func = partial(error_of_type, error_type=exceptions)
  933. return any(func(handler) for handler in handlers)
  934. def get_exception_handlers(
  935. node: nodes.NodeNG, exception: type[Exception] | str = Exception
  936. ) -> list[nodes.ExceptHandler] | None:
  937. """Return the collections of handlers handling the exception in arguments.
  938. Args:
  939. node (nodes.NodeNG): A node that is potentially wrapped in a try except.
  940. exception (builtin.Exception or str): exception or name of the exception.
  941. Returns:
  942. list: the collection of handlers that are handling the exception or None.
  943. """
  944. context = find_try_except_wrapper_node(node)
  945. if isinstance(context, nodes.TryExcept):
  946. return [
  947. handler for handler in context.handlers if error_of_type(handler, exception)
  948. ]
  949. return []
  950. def get_contextlib_with_statements(node: nodes.NodeNG) -> Iterator[nodes.With]:
  951. """Get all contextlib.with statements in the ancestors of the given node."""
  952. for with_node in node.node_ancestors():
  953. if isinstance(with_node, nodes.With):
  954. yield with_node
  955. def _suppresses_exception(
  956. call: nodes.Call, exception: type[Exception] | str = Exception
  957. ) -> bool:
  958. """Check if the given node suppresses the given exception."""
  959. if not isinstance(exception, str):
  960. exception = exception.__name__
  961. for arg in call.args:
  962. inferred = safe_infer(arg)
  963. if isinstance(inferred, nodes.ClassDef):
  964. if inferred.name == exception:
  965. return True
  966. elif isinstance(inferred, nodes.Tuple):
  967. for elt in inferred.elts:
  968. inferred_elt = safe_infer(elt)
  969. if (
  970. isinstance(inferred_elt, nodes.ClassDef)
  971. and inferred_elt.name == exception
  972. ):
  973. return True
  974. return False
  975. def get_contextlib_suppressors(
  976. node: nodes.NodeNG, exception: type[Exception] | str = Exception
  977. ) -> Iterator[nodes.With]:
  978. """Return the contextlib suppressors handling the exception.
  979. Args:
  980. node (nodes.NodeNG): A node that is potentially wrapped in a contextlib.suppress.
  981. exception (builtin.Exception): exception or name of the exception.
  982. Yields:
  983. nodes.With: A with node that is suppressing the exception.
  984. """
  985. for with_node in get_contextlib_with_statements(node):
  986. for item, _ in with_node.items:
  987. if isinstance(item, nodes.Call):
  988. inferred = safe_infer(item.func)
  989. if (
  990. isinstance(inferred, nodes.ClassDef)
  991. and inferred.qname() == "contextlib.suppress"
  992. ):
  993. if _suppresses_exception(item, exception):
  994. yield with_node
  995. def is_node_inside_try_except(node: nodes.Raise) -> bool:
  996. """Check if the node is directly under a Try/Except statement
  997. (but not under an ExceptHandler!).
  998. Args:
  999. node (nodes.Raise): the node raising the exception.
  1000. Returns:
  1001. bool: True if the node is inside a try/except statement, False otherwise.
  1002. """
  1003. context = find_try_except_wrapper_node(node)
  1004. return isinstance(context, nodes.TryExcept)
  1005. def node_ignores_exception(
  1006. node: nodes.NodeNG, exception: type[Exception] | str = Exception
  1007. ) -> bool:
  1008. """Check if the node is in a TryExcept which handles the given exception.
  1009. If the exception is not given, the function is going to look for bare
  1010. excepts.
  1011. """
  1012. managing_handlers = get_exception_handlers(node, exception)
  1013. if managing_handlers:
  1014. return True
  1015. return any(get_contextlib_suppressors(node, exception))
  1016. def class_is_abstract(node: nodes.ClassDef) -> bool:
  1017. """Return true if the given class node should be considered as an abstract
  1018. class.
  1019. """
  1020. # Protocol classes are considered "abstract"
  1021. if is_protocol_class(node):
  1022. return True
  1023. # Only check for explicit metaclass=ABCMeta on this specific class
  1024. meta = node.declared_metaclass()
  1025. if meta is not None:
  1026. if meta.name == "ABCMeta" and meta.root().name in ABC_MODULES:
  1027. return True
  1028. for ancestor in node.ancestors():
  1029. if ancestor.name == "ABC" and ancestor.root().name in ABC_MODULES:
  1030. # abc.ABC inheritance
  1031. return True
  1032. for method in node.methods():
  1033. if method.parent.frame(future=True) is node:
  1034. if method.is_abstract(pass_is_abstract=False):
  1035. return True
  1036. return False
  1037. def _supports_protocol_method(value: nodes.NodeNG, attr: str) -> bool:
  1038. try:
  1039. attributes = value.getattr(attr)
  1040. except astroid.NotFoundError:
  1041. return False
  1042. first = attributes[0]
  1043. # Return False if a constant is assigned
  1044. if isinstance(first, nodes.AssignName):
  1045. this_assign_parent = get_node_first_ancestor_of_type(
  1046. first, (nodes.Assign, nodes.NamedExpr)
  1047. )
  1048. if this_assign_parent is None: # pragma: no cover
  1049. # Cannot imagine this being None, but return True to avoid false positives
  1050. return True
  1051. if isinstance(this_assign_parent.value, nodes.BaseContainer):
  1052. if all(isinstance(n, nodes.Const) for n in this_assign_parent.value.elts):
  1053. return False
  1054. if isinstance(this_assign_parent.value, nodes.Const):
  1055. return False
  1056. return True
  1057. def is_comprehension(node: nodes.NodeNG) -> bool:
  1058. comprehensions = (
  1059. nodes.ListComp,
  1060. nodes.SetComp,
  1061. nodes.DictComp,
  1062. nodes.GeneratorExp,
  1063. )
  1064. return isinstance(node, comprehensions)
  1065. def _supports_mapping_protocol(value: nodes.NodeNG) -> bool:
  1066. return _supports_protocol_method(
  1067. value, GETITEM_METHOD
  1068. ) and _supports_protocol_method(value, KEYS_METHOD)
  1069. def _supports_membership_test_protocol(value: nodes.NodeNG) -> bool:
  1070. return _supports_protocol_method(value, CONTAINS_METHOD)
  1071. def _supports_iteration_protocol(value: nodes.NodeNG) -> bool:
  1072. return _supports_protocol_method(value, ITER_METHOD) or _supports_protocol_method(
  1073. value, GETITEM_METHOD
  1074. )
  1075. def _supports_async_iteration_protocol(value: nodes.NodeNG) -> bool:
  1076. return _supports_protocol_method(value, AITER_METHOD)
  1077. def _supports_getitem_protocol(value: nodes.NodeNG) -> bool:
  1078. return _supports_protocol_method(value, GETITEM_METHOD)
  1079. def _supports_setitem_protocol(value: nodes.NodeNG) -> bool:
  1080. return _supports_protocol_method(value, SETITEM_METHOD)
  1081. def _supports_delitem_protocol(value: nodes.NodeNG) -> bool:
  1082. return _supports_protocol_method(value, DELITEM_METHOD)
  1083. def _is_abstract_class_name(name: str) -> bool:
  1084. lname = name.lower()
  1085. is_mixin = lname.endswith("mixin")
  1086. is_abstract = lname.startswith("abstract")
  1087. is_base = lname.startswith("base") or lname.endswith("base")
  1088. return is_mixin or is_abstract or is_base
  1089. def is_inside_abstract_class(node: nodes.NodeNG) -> bool:
  1090. while node is not None:
  1091. if isinstance(node, nodes.ClassDef):
  1092. if class_is_abstract(node):
  1093. return True
  1094. name = getattr(node, "name", None)
  1095. if name is not None and _is_abstract_class_name(name):
  1096. return True
  1097. node = node.parent
  1098. return False
  1099. def _supports_protocol(
  1100. value: nodes.NodeNG, protocol_callback: Callable[[nodes.NodeNG], bool]
  1101. ) -> bool:
  1102. if isinstance(value, nodes.ClassDef):
  1103. if not has_known_bases(value):
  1104. return True
  1105. # classobj can only be iterable if it has an iterable metaclass
  1106. meta = value.metaclass()
  1107. if meta is not None:
  1108. if protocol_callback(meta):
  1109. return True
  1110. if isinstance(value, astroid.BaseInstance):
  1111. if not has_known_bases(value):
  1112. return True
  1113. if value.has_dynamic_getattr():
  1114. return True
  1115. if protocol_callback(value):
  1116. return True
  1117. if isinstance(value, nodes.ComprehensionScope):
  1118. return True
  1119. if (
  1120. isinstance(value, astroid.bases.Proxy)
  1121. and isinstance(value._proxied, astroid.BaseInstance)
  1122. and has_known_bases(value._proxied)
  1123. ):
  1124. value = value._proxied
  1125. return protocol_callback(value)
  1126. return False
  1127. def is_iterable(value: nodes.NodeNG, check_async: bool = False) -> bool:
  1128. if check_async:
  1129. protocol_check = _supports_async_iteration_protocol
  1130. else:
  1131. protocol_check = _supports_iteration_protocol
  1132. return _supports_protocol(value, protocol_check)
  1133. def is_mapping(value: nodes.NodeNG) -> bool:
  1134. return _supports_protocol(value, _supports_mapping_protocol)
  1135. def supports_membership_test(value: nodes.NodeNG) -> bool:
  1136. supported = _supports_protocol(value, _supports_membership_test_protocol)
  1137. return supported or is_iterable(value)
  1138. def supports_getitem(value: nodes.NodeNG, node: nodes.NodeNG) -> bool:
  1139. if isinstance(value, nodes.ClassDef):
  1140. if _supports_protocol_method(value, CLASS_GETITEM_METHOD):
  1141. return True
  1142. if is_postponed_evaluation_enabled(node) and is_node_in_type_annotation_context(
  1143. node
  1144. ):
  1145. return True
  1146. return _supports_protocol(value, _supports_getitem_protocol)
  1147. def supports_setitem(value: nodes.NodeNG, _: nodes.NodeNG) -> bool:
  1148. return _supports_protocol(value, _supports_setitem_protocol)
  1149. def supports_delitem(value: nodes.NodeNG, _: nodes.NodeNG) -> bool:
  1150. return _supports_protocol(value, _supports_delitem_protocol)
  1151. def _get_python_type_of_node(node: nodes.NodeNG) -> str | None:
  1152. pytype: Callable[[], str] | None = getattr(node, "pytype", None)
  1153. if callable(pytype):
  1154. return pytype()
  1155. return None
  1156. @lru_cache(maxsize=1024)
  1157. def safe_infer(
  1158. node: nodes.NodeNG,
  1159. context: InferenceContext | None = None,
  1160. *,
  1161. compare_constants: bool = False,
  1162. ) -> InferenceResult | None:
  1163. """Return the inferred value for the given node.
  1164. Return None if inference failed or if there is some ambiguity (more than
  1165. one node has been inferred of different types).
  1166. If compare_constants is True and if multiple constants are inferred,
  1167. unequal inferred values are also considered ambiguous and return None.
  1168. """
  1169. inferred_types: set[str | None] = set()
  1170. try:
  1171. infer_gen = node.infer(context=context)
  1172. value = next(infer_gen)
  1173. except astroid.InferenceError:
  1174. return None
  1175. except Exception as e: # pragma: no cover
  1176. raise AstroidError from e
  1177. if not isinstance(value, util.UninferableBase):
  1178. inferred_types.add(_get_python_type_of_node(value))
  1179. # pylint: disable = too-many-try-statements
  1180. try:
  1181. for inferred in infer_gen:
  1182. inferred_type = _get_python_type_of_node(inferred)
  1183. if inferred_type not in inferred_types:
  1184. return None # If there is ambiguity on the inferred node.
  1185. if (
  1186. compare_constants
  1187. and isinstance(inferred, nodes.Const)
  1188. and isinstance(value, nodes.Const)
  1189. and inferred.value != value.value
  1190. ):
  1191. return None
  1192. if (
  1193. isinstance(inferred, nodes.FunctionDef)
  1194. and inferred.args.args is not None
  1195. and isinstance(value, nodes.FunctionDef)
  1196. and value.args.args is not None
  1197. and len(inferred.args.args) != len(value.args.args)
  1198. ):
  1199. return None # Different number of arguments indicates ambiguity
  1200. except astroid.InferenceError:
  1201. return None # There is some kind of ambiguity
  1202. except StopIteration:
  1203. return value
  1204. except Exception as e: # pragma: no cover
  1205. raise AstroidError from e
  1206. return value if len(inferred_types) <= 1 else None
  1207. @lru_cache(maxsize=512)
  1208. def infer_all(
  1209. node: nodes.NodeNG, context: InferenceContext | None = None
  1210. ) -> list[InferenceResult]:
  1211. try:
  1212. return list(node.infer(context=context))
  1213. except astroid.InferenceError:
  1214. return []
  1215. except Exception as e: # pragma: no cover
  1216. raise AstroidError from e
  1217. def has_known_bases(
  1218. klass: nodes.ClassDef, context: InferenceContext | None = None
  1219. ) -> bool:
  1220. """Return true if all base classes of a class could be inferred."""
  1221. try:
  1222. return klass._all_bases_known # type: ignore[no-any-return]
  1223. except AttributeError:
  1224. pass
  1225. for base in klass.bases:
  1226. result = safe_infer(base, context=context)
  1227. if (
  1228. not isinstance(result, nodes.ClassDef)
  1229. or result is klass
  1230. or not has_known_bases(result, context=context)
  1231. ):
  1232. klass._all_bases_known = False
  1233. return False
  1234. klass._all_bases_known = True
  1235. return True
  1236. def is_none(node: nodes.NodeNG) -> bool:
  1237. return (
  1238. node is None
  1239. or (isinstance(node, nodes.Const) and node.value is None)
  1240. or (isinstance(node, nodes.Name) and node.name == "None")
  1241. )
  1242. def node_type(node: nodes.NodeNG) -> SuccessfulInferenceResult | None:
  1243. """Return the inferred type for `node`.
  1244. If there is more than one possible type, or if inferred type is Uninferable or None,
  1245. return None
  1246. """
  1247. # check there is only one possible type for the assign node. Else we
  1248. # don't handle it for now
  1249. types: set[SuccessfulInferenceResult] = set()
  1250. try:
  1251. for var_type in node.infer():
  1252. if isinstance(var_type, util.UninferableBase) or is_none(var_type):
  1253. continue
  1254. types.add(var_type)
  1255. if len(types) > 1:
  1256. return None
  1257. except astroid.InferenceError:
  1258. return None
  1259. return types.pop() if types else None
  1260. def is_registered_in_singledispatch_function(node: nodes.FunctionDef) -> bool:
  1261. """Check if the given function node is a singledispatch function."""
  1262. singledispatch_qnames = (
  1263. "functools.singledispatch",
  1264. "singledispatch.singledispatch",
  1265. )
  1266. if not isinstance(node, nodes.FunctionDef):
  1267. return False
  1268. decorators = node.decorators.nodes if node.decorators else []
  1269. for decorator in decorators:
  1270. # func.register are function calls or register attributes
  1271. # when the function is annotated with types
  1272. if isinstance(decorator, nodes.Call):
  1273. func = decorator.func
  1274. elif isinstance(decorator, nodes.Attribute):
  1275. func = decorator
  1276. else:
  1277. continue
  1278. if not isinstance(func, nodes.Attribute) or func.attrname != "register":
  1279. continue
  1280. try:
  1281. func_def = next(func.expr.infer())
  1282. except astroid.InferenceError:
  1283. continue
  1284. if isinstance(func_def, nodes.FunctionDef):
  1285. return decorated_with(func_def, singledispatch_qnames)
  1286. return False
  1287. def find_inferred_fn_from_register(node: nodes.NodeNG) -> nodes.FunctionDef | None:
  1288. # func.register are function calls or register attributes
  1289. # when the function is annotated with types
  1290. if isinstance(node, nodes.Call):
  1291. func = node.func
  1292. elif isinstance(node, nodes.Attribute):
  1293. func = node
  1294. else:
  1295. return None
  1296. if not isinstance(func, nodes.Attribute) or func.attrname != "register":
  1297. return None
  1298. func_def = safe_infer(func.expr)
  1299. if not isinstance(func_def, nodes.FunctionDef):
  1300. return None
  1301. return func_def
  1302. def is_registered_in_singledispatchmethod_function(node: nodes.FunctionDef) -> bool:
  1303. """Check if the given function node is a singledispatchmethod function."""
  1304. singledispatchmethod_qnames = (
  1305. "functools.singledispatchmethod",
  1306. "singledispatch.singledispatchmethod",
  1307. )
  1308. decorators = node.decorators.nodes if node.decorators else []
  1309. for decorator in decorators:
  1310. func_def = find_inferred_fn_from_register(decorator)
  1311. if func_def:
  1312. return decorated_with(func_def, singledispatchmethod_qnames)
  1313. return False
  1314. def get_node_last_lineno(node: nodes.NodeNG) -> int:
  1315. """Get the last lineno of the given node.
  1316. For a simple statement this will just be node.lineno,
  1317. but for a node that has child statements (e.g. a method) this will be the lineno of the last
  1318. child statement recursively.
  1319. """
  1320. # 'finalbody' is always the last clause in a try statement, if present
  1321. if getattr(node, "finalbody", False):
  1322. return get_node_last_lineno(node.finalbody[-1])
  1323. # For if, while, and for statements 'orelse' is always the last clause.
  1324. # For try statements 'orelse' is the last in the absence of a 'finalbody'
  1325. if getattr(node, "orelse", False):
  1326. return get_node_last_lineno(node.orelse[-1])
  1327. # try statements have the 'handlers' last if there is no 'orelse' or 'finalbody'
  1328. if getattr(node, "handlers", False):
  1329. return get_node_last_lineno(node.handlers[-1])
  1330. # All compound statements have a 'body'
  1331. if getattr(node, "body", False):
  1332. return get_node_last_lineno(node.body[-1])
  1333. # Not a compound statement
  1334. return node.lineno # type: ignore[no-any-return]
  1335. def is_postponed_evaluation_enabled(node: nodes.NodeNG) -> bool:
  1336. """Check if the postponed evaluation of annotations is enabled."""
  1337. module = node.root()
  1338. return "annotations" in module.future_imports
  1339. def is_class_subscriptable_pep585_with_postponed_evaluation_enabled(
  1340. value: nodes.ClassDef, node: nodes.NodeNG
  1341. ) -> bool:
  1342. """Check if class is subscriptable with PEP 585 and
  1343. postponed evaluation enabled.
  1344. """
  1345. warnings.warn(
  1346. "'is_class_subscriptable_pep585_with_postponed_evaluation_enabled' has been "
  1347. "deprecated and will be removed in pylint 3.0. "
  1348. "Use 'is_postponed_evaluation_enabled(node) and "
  1349. "is_node_in_type_annotation_context(node)' instead.",
  1350. DeprecationWarning,
  1351. stacklevel=2,
  1352. )
  1353. return (
  1354. is_postponed_evaluation_enabled(node)
  1355. and value.qname() in SUBSCRIPTABLE_CLASSES_PEP585
  1356. and is_node_in_type_annotation_context(node)
  1357. )
  1358. def is_node_in_type_annotation_context(node: nodes.NodeNG) -> bool:
  1359. """Check if node is in type annotation context.
  1360. Check for 'AnnAssign', function 'Arguments',
  1361. or part of function return type annotation.
  1362. """
  1363. # pylint: disable=too-many-boolean-expressions
  1364. current_node, parent_node = node, node.parent
  1365. while True:
  1366. if (
  1367. isinstance(parent_node, nodes.AnnAssign)
  1368. and parent_node.annotation == current_node
  1369. or isinstance(parent_node, nodes.Arguments)
  1370. and current_node
  1371. in (
  1372. *parent_node.annotations,
  1373. *parent_node.posonlyargs_annotations,
  1374. *parent_node.kwonlyargs_annotations,
  1375. parent_node.varargannotation,
  1376. parent_node.kwargannotation,
  1377. )
  1378. or isinstance(parent_node, nodes.FunctionDef)
  1379. and parent_node.returns == current_node
  1380. ):
  1381. return True
  1382. current_node, parent_node = parent_node, parent_node.parent
  1383. if isinstance(parent_node, nodes.Module):
  1384. return False
  1385. def is_subclass_of(child: nodes.ClassDef, parent: nodes.ClassDef) -> bool:
  1386. """Check if first node is a subclass of second node.
  1387. :param child: Node to check for subclass.
  1388. :param parent: Node to check for superclass.
  1389. :returns: True if child is derived from parent. False otherwise.
  1390. """
  1391. if not all(isinstance(node, nodes.ClassDef) for node in (child, parent)):
  1392. return False
  1393. for ancestor in child.ancestors():
  1394. try:
  1395. if astroid.helpers.is_subtype(ancestor, parent):
  1396. return True
  1397. except astroid.exceptions._NonDeducibleTypeHierarchy:
  1398. continue
  1399. return False
  1400. @lru_cache(maxsize=1024)
  1401. def is_overload_stub(node: nodes.NodeNG) -> bool:
  1402. """Check if a node is a function stub decorated with typing.overload.
  1403. :param node: Node to check.
  1404. :returns: True if node is an overload function stub. False otherwise.
  1405. """
  1406. decorators = getattr(node, "decorators", None)
  1407. return bool(decorators and decorated_with(node, ["typing.overload", "overload"]))
  1408. def is_protocol_class(cls: nodes.NodeNG) -> bool:
  1409. """Check if the given node represents a protocol class.
  1410. :param cls: The node to check
  1411. :returns: True if the node is or inherits from typing.Protocol directly, false otherwise.
  1412. """
  1413. if not isinstance(cls, nodes.ClassDef):
  1414. return False
  1415. # Return if klass is protocol
  1416. if cls.qname() in TYPING_PROTOCOLS:
  1417. return True
  1418. for base in cls.bases:
  1419. try:
  1420. for inf_base in base.infer():
  1421. if inf_base.qname() in TYPING_PROTOCOLS:
  1422. return True
  1423. except astroid.InferenceError:
  1424. continue
  1425. return False
  1426. def is_call_of_name(node: nodes.NodeNG, name: str) -> bool:
  1427. """Checks if node is a function call with the given name."""
  1428. return (
  1429. isinstance(node, nodes.Call)
  1430. and isinstance(node.func, nodes.Name)
  1431. and node.func.name == name
  1432. )
  1433. def is_test_condition(
  1434. node: nodes.NodeNG,
  1435. parent: nodes.NodeNG | None = None,
  1436. ) -> bool:
  1437. """Returns true if the given node is being tested for truthiness."""
  1438. parent = parent or node.parent
  1439. if isinstance(parent, (nodes.While, nodes.If, nodes.IfExp, nodes.Assert)):
  1440. return node is parent.test or parent.test.parent_of(node)
  1441. if isinstance(parent, nodes.Comprehension):
  1442. return node in parent.ifs
  1443. return is_call_of_name(parent, "bool") and parent.parent_of(node)
  1444. def is_classdef_type(node: nodes.ClassDef) -> bool:
  1445. """Test if ClassDef node is Type."""
  1446. if node.name == "type":
  1447. return True
  1448. return any(isinstance(b, nodes.Name) and b.name == "type" for b in node.bases)
  1449. def is_attribute_typed_annotation(
  1450. node: nodes.ClassDef | astroid.Instance, attr_name: str
  1451. ) -> bool:
  1452. """Test if attribute is typed annotation in current node
  1453. or any base nodes.
  1454. """
  1455. attribute = node.locals.get(attr_name, [None])[0]
  1456. if (
  1457. attribute
  1458. and isinstance(attribute, nodes.AssignName)
  1459. and isinstance(attribute.parent, nodes.AnnAssign)
  1460. ):
  1461. return True
  1462. for base in node.bases:
  1463. inferred = safe_infer(base)
  1464. if (
  1465. inferred
  1466. and isinstance(inferred, nodes.ClassDef)
  1467. and is_attribute_typed_annotation(inferred, attr_name)
  1468. ):
  1469. return True
  1470. return False
  1471. def is_enum(node: nodes.ClassDef) -> bool:
  1472. return node.name == "Enum" and node.root().name == "enum" # type: ignore[no-any-return]
  1473. def is_assign_name_annotated_with(node: nodes.AssignName, typing_name: str) -> bool:
  1474. """Test if AssignName node has `typing_name` annotation.
  1475. Especially useful to check for `typing._SpecialForm` instances
  1476. like: `Union`, `Optional`, `Literal`, `ClassVar`, `Final`.
  1477. """
  1478. if not isinstance(node.parent, nodes.AnnAssign):
  1479. return False
  1480. annotation = node.parent.annotation
  1481. if isinstance(annotation, nodes.Subscript):
  1482. annotation = annotation.value
  1483. if (
  1484. isinstance(annotation, nodes.Name)
  1485. and annotation.name == typing_name
  1486. or isinstance(annotation, nodes.Attribute)
  1487. and annotation.attrname == typing_name
  1488. ):
  1489. return True
  1490. return False
  1491. def get_iterating_dictionary_name(node: nodes.For | nodes.Comprehension) -> str | None:
  1492. """Get the name of the dictionary which keys are being iterated over on
  1493. a ``nodes.For`` or ``nodes.Comprehension`` node.
  1494. If the iterating object is not either the keys method of a dictionary
  1495. or a dictionary itself, this returns None.
  1496. """
  1497. # Is it a proper keys call?
  1498. if (
  1499. isinstance(node.iter, nodes.Call)
  1500. and isinstance(node.iter.func, nodes.Attribute)
  1501. and node.iter.func.attrname == "keys"
  1502. ):
  1503. inferred = safe_infer(node.iter.func)
  1504. if not isinstance(inferred, astroid.BoundMethod):
  1505. return None
  1506. return node.iter.as_string().rpartition(".keys")[0] # type: ignore[no-any-return]
  1507. # Is it a dictionary?
  1508. if isinstance(node.iter, (nodes.Name, nodes.Attribute)):
  1509. inferred = safe_infer(node.iter)
  1510. if not isinstance(inferred, nodes.Dict):
  1511. return None
  1512. return node.iter.as_string() # type: ignore[no-any-return]
  1513. return None
  1514. def get_subscript_const_value(node: nodes.Subscript) -> nodes.Const:
  1515. """Returns the value 'subscript.slice' of a Subscript node.
  1516. :param node: Subscript Node to extract value from
  1517. :returns: Const Node containing subscript value
  1518. :raises InferredTypeError: if the subscript node cannot be inferred as a Const
  1519. """
  1520. inferred = safe_infer(node.slice)
  1521. if not isinstance(inferred, nodes.Const):
  1522. raise InferredTypeError("Subscript.slice cannot be inferred as a nodes.Const")
  1523. return inferred
  1524. def get_import_name(importnode: ImportNode, modname: str | None) -> str | None:
  1525. """Get a prepared module name from the given import node.
  1526. In the case of relative imports, this will return the
  1527. absolute qualified module name, which might be useful
  1528. for debugging. Otherwise, the initial module name
  1529. is returned unchanged.
  1530. :param importnode: node representing import statement.
  1531. :param modname: module name from import statement.
  1532. :returns: absolute qualified module name of the module
  1533. used in import.
  1534. """
  1535. if isinstance(importnode, nodes.ImportFrom) and importnode.level:
  1536. root = importnode.root()
  1537. if isinstance(root, nodes.Module):
  1538. try:
  1539. return root.relative_to_absolute_name( # type: ignore[no-any-return]
  1540. modname, level=importnode.level
  1541. )
  1542. except TooManyLevelsError:
  1543. return modname
  1544. return modname
  1545. def is_sys_guard(node: nodes.If) -> bool:
  1546. """Return True if IF stmt is a sys.version_info guard.
  1547. >>> import sys
  1548. >>> if sys.version_info > (3, 8):
  1549. >>> from typing import Literal
  1550. >>> else:
  1551. >>> from typing_extensions import Literal
  1552. """
  1553. if isinstance(node.test, nodes.Compare):
  1554. value = node.test.left
  1555. if isinstance(value, nodes.Subscript):
  1556. value = value.value
  1557. if (
  1558. isinstance(value, nodes.Attribute)
  1559. and value.as_string() == "sys.version_info"
  1560. ):
  1561. return True
  1562. return False
  1563. def is_typing_guard(node: nodes.If) -> bool:
  1564. """Return True if IF stmt is a typing guard.
  1565. >>> from typing import TYPE_CHECKING
  1566. >>> if TYPE_CHECKING:
  1567. >>> from xyz import a
  1568. """
  1569. warnings.warn(
  1570. "This method will be removed in pylint 3.0; use in_type_checking_block() instead.",
  1571. DeprecationWarning,
  1572. stacklevel=2,
  1573. ) # pragma: no cover
  1574. return isinstance(
  1575. node.test, (nodes.Name, nodes.Attribute)
  1576. ) and node.test.as_string().endswith("TYPE_CHECKING")
  1577. def is_node_in_typing_guarded_import_block(node: nodes.NodeNG) -> bool:
  1578. """Return True if node is part for guarded `typing.TYPE_CHECKING` if block."""
  1579. warnings.warn(
  1580. "This method will be removed in pylint 3.0; use in_type_checking_block() instead.",
  1581. DeprecationWarning,
  1582. stacklevel=2,
  1583. ) # pragma: no cover
  1584. return isinstance(node.parent, nodes.If) and is_typing_guard(node.parent)
  1585. def is_node_in_guarded_import_block(node: nodes.NodeNG) -> bool:
  1586. """Return True if node is part for guarded if block.
  1587. I.e. `sys.version_info` or `typing.TYPE_CHECKING`
  1588. """
  1589. warnings.warn(
  1590. "This method will be removed in pylint 3.0; use in_type_checking_block() instead.",
  1591. DeprecationWarning,
  1592. stacklevel=2,
  1593. ) # pragma: no cover
  1594. return isinstance(node.parent, nodes.If) and (
  1595. is_sys_guard(node.parent) or is_typing_guard(node.parent)
  1596. )
  1597. def is_reassigned_after_current(node: nodes.NodeNG, varname: str) -> bool:
  1598. """Check if the given variable name is reassigned in the same scope after the
  1599. current node.
  1600. """
  1601. return any(
  1602. a.name == varname and a.lineno > node.lineno
  1603. for a in node.scope().nodes_of_class(
  1604. (nodes.AssignName, nodes.ClassDef, nodes.FunctionDef)
  1605. )
  1606. )
  1607. def is_deleted_after_current(node: nodes.NodeNG, varname: str) -> bool:
  1608. """Check if the given variable name is deleted in the same scope after the current
  1609. node.
  1610. """
  1611. return any(
  1612. getattr(target, "name", None) == varname and target.lineno > node.lineno
  1613. for del_node in node.scope().nodes_of_class(nodes.Delete)
  1614. for target in del_node.targets
  1615. )
  1616. def is_function_body_ellipsis(node: nodes.FunctionDef) -> bool:
  1617. """Checks whether a function body only consists of a single Ellipsis."""
  1618. return (
  1619. len(node.body) == 1
  1620. and isinstance(node.body[0], nodes.Expr)
  1621. and isinstance(node.body[0].value, nodes.Const)
  1622. and node.body[0].value.value == Ellipsis
  1623. )
  1624. def is_base_container(node: nodes.NodeNG | None) -> bool:
  1625. return isinstance(node, nodes.BaseContainer) and not node.elts
  1626. def is_empty_dict_literal(node: nodes.NodeNG | None) -> bool:
  1627. return isinstance(node, nodes.Dict) and not node.items
  1628. def is_empty_str_literal(node: nodes.NodeNG | None) -> bool:
  1629. return (
  1630. isinstance(node, nodes.Const) and isinstance(node.value, str) and not node.value
  1631. )
  1632. def returns_bool(node: nodes.NodeNG) -> bool:
  1633. """Returns true if a node is a nodes.Return that returns a constant boolean."""
  1634. return (
  1635. isinstance(node, nodes.Return)
  1636. and isinstance(node.value, nodes.Const)
  1637. and isinstance(node.value.value, bool)
  1638. )
  1639. def assigned_bool(node: nodes.NodeNG) -> bool:
  1640. """Returns true if a node is a nodes.Assign that returns a constant boolean."""
  1641. return (
  1642. isinstance(node, nodes.Assign)
  1643. and isinstance(node.value, nodes.Const)
  1644. and isinstance(node.value.value, bool)
  1645. )
  1646. def get_node_first_ancestor_of_type(
  1647. node: nodes.NodeNG, ancestor_type: type[_NodeT] | tuple[type[_NodeT], ...]
  1648. ) -> _NodeT | None:
  1649. """Return the first parent node that is any of the provided types (or None)."""
  1650. for ancestor in node.node_ancestors():
  1651. if isinstance(ancestor, ancestor_type):
  1652. return ancestor # type: ignore[no-any-return]
  1653. return None
  1654. def get_node_first_ancestor_of_type_and_its_child(
  1655. node: nodes.NodeNG, ancestor_type: type[_NodeT] | tuple[type[_NodeT], ...]
  1656. ) -> tuple[None, None] | tuple[_NodeT, nodes.NodeNG]:
  1657. """Modified version of get_node_first_ancestor_of_type to also return the
  1658. descendant visited directly before reaching the sought ancestor.
  1659. Useful for extracting whether a statement is guarded by a try, except, or finally
  1660. when searching for a TryFinally ancestor.
  1661. """
  1662. child = node
  1663. for ancestor in node.node_ancestors():
  1664. if isinstance(ancestor, ancestor_type):
  1665. return (ancestor, child)
  1666. child = ancestor
  1667. return None, None
  1668. def in_type_checking_block(node: nodes.NodeNG) -> bool:
  1669. """Check if a node is guarded by a TYPE_CHECKING guard."""
  1670. for ancestor in node.node_ancestors():
  1671. if not isinstance(ancestor, nodes.If):
  1672. continue
  1673. if isinstance(ancestor.test, nodes.Name):
  1674. if ancestor.test.name != "TYPE_CHECKING":
  1675. continue
  1676. lookup_result = ancestor.test.lookup(ancestor.test.name)[1]
  1677. if not lookup_result:
  1678. return False
  1679. maybe_import_from = lookup_result[0]
  1680. if (
  1681. isinstance(maybe_import_from, nodes.ImportFrom)
  1682. and maybe_import_from.modname == "typing"
  1683. ):
  1684. return True
  1685. inferred = safe_infer(ancestor.test)
  1686. if isinstance(inferred, nodes.Const) and inferred.value is False:
  1687. return True
  1688. elif isinstance(ancestor.test, nodes.Attribute):
  1689. if ancestor.test.attrname != "TYPE_CHECKING":
  1690. continue
  1691. inferred_module = safe_infer(ancestor.test.expr)
  1692. if (
  1693. isinstance(inferred_module, nodes.Module)
  1694. and inferred_module.name == "typing"
  1695. ):
  1696. return True
  1697. return False
  1698. def is_typing_member(node: nodes.NodeNG, names_to_check: tuple[str, ...]) -> bool:
  1699. """Check if `node` is a member of the `typing` module and has one of the names from
  1700. `names_to_check`.
  1701. """
  1702. if isinstance(node, nodes.Name):
  1703. try:
  1704. import_from = node.lookup(node.name)[1][0]
  1705. except IndexError:
  1706. return False
  1707. if isinstance(import_from, nodes.ImportFrom):
  1708. return (
  1709. import_from.modname == "typing"
  1710. and import_from.real_name(node.name) in names_to_check
  1711. )
  1712. elif isinstance(node, nodes.Attribute):
  1713. inferred_module = safe_infer(node.expr)
  1714. return (
  1715. isinstance(inferred_module, nodes.Module)
  1716. and inferred_module.name == "typing"
  1717. and node.attrname in names_to_check
  1718. )
  1719. return False
  1720. @lru_cache()
  1721. def in_for_else_branch(parent: nodes.NodeNG, stmt: nodes.Statement) -> bool:
  1722. """Returns True if stmt is inside the else branch for a parent For stmt."""
  1723. return isinstance(parent, nodes.For) and any(
  1724. else_stmt.parent_of(stmt) or else_stmt == stmt for else_stmt in parent.orelse
  1725. )
  1726. def find_assigned_names_recursive(
  1727. target: nodes.AssignName | nodes.BaseContainer,
  1728. ) -> Iterator[str]:
  1729. """Yield the names of assignment targets, accounting for nested ones."""
  1730. if isinstance(target, nodes.AssignName):
  1731. if target.name is not None:
  1732. yield target.name
  1733. elif isinstance(target, nodes.BaseContainer):
  1734. for elt in target.elts:
  1735. yield from find_assigned_names_recursive(elt)
  1736. def has_starred_node_recursive(
  1737. node: nodes.For | nodes.Comprehension | nodes.Set,
  1738. ) -> Iterator[bool]:
  1739. """Yield ``True`` if a Starred node is found recursively."""
  1740. if isinstance(node, nodes.Starred):
  1741. yield True
  1742. elif isinstance(node, nodes.Set):
  1743. for elt in node.elts:
  1744. yield from has_starred_node_recursive(elt)
  1745. elif isinstance(node, (nodes.For, nodes.Comprehension)):
  1746. for elt in node.iter.elts:
  1747. yield from has_starred_node_recursive(elt)
  1748. def is_hashable(node: nodes.NodeNG) -> bool:
  1749. """Return whether any inferred value of `node` is hashable.
  1750. When finding ambiguity, return True.
  1751. """
  1752. # pylint: disable = too-many-try-statements
  1753. try:
  1754. for inferred in node.infer():
  1755. if isinstance(inferred, (nodes.ClassDef, util.UninferableBase)):
  1756. return True
  1757. if not hasattr(inferred, "igetattr"):
  1758. return True
  1759. hash_fn = next(inferred.igetattr("__hash__"))
  1760. if hash_fn.parent is inferred:
  1761. return True
  1762. if getattr(hash_fn, "value", True) is not None:
  1763. return True
  1764. return False
  1765. except astroid.InferenceError:
  1766. return True
  1767. def _is_target_name_in_binop_side(
  1768. target: nodes.AssignName | nodes.AssignAttr, side: nodes.NodeNG | None
  1769. ) -> bool:
  1770. """Determine whether the target name-like node is referenced in the side node."""
  1771. if isinstance(side, nodes.Name):
  1772. if isinstance(target, nodes.AssignName):
  1773. return target.name == side.name # type: ignore[no-any-return]
  1774. return False
  1775. if isinstance(side, nodes.Attribute) and isinstance(target, nodes.AssignAttr):
  1776. return target.as_string() == side.as_string() # type: ignore[no-any-return]
  1777. return False
  1778. def is_augmented_assign(node: nodes.Assign) -> tuple[bool, str]:
  1779. """Determine if the node is assigning itself (with modifications) to itself.
  1780. For example: x = 1 + x
  1781. """
  1782. if not isinstance(node.value, nodes.BinOp):
  1783. return False, ""
  1784. binop = node.value
  1785. target = node.targets[0]
  1786. if not isinstance(target, (nodes.AssignName, nodes.AssignAttr)):
  1787. return False, ""
  1788. # We don't want to catch x = "1" + x or x = "%s" % x
  1789. if isinstance(binop.left, nodes.Const) and isinstance(
  1790. binop.left.value, (str, bytes)
  1791. ):
  1792. return False, ""
  1793. # This could probably be improved but for now we disregard all assignments from calls
  1794. if isinstance(binop.left, nodes.Call) or isinstance(binop.right, nodes.Call):
  1795. return False, ""
  1796. if _is_target_name_in_binop_side(target, binop.left):
  1797. return True, binop.op
  1798. if (
  1799. # Unless an operator is commutative, we should not raise (i.e. x = 3/x)
  1800. binop.op in COMMUTATIVE_OPERATORS
  1801. and _is_target_name_in_binop_side(target, binop.right)
  1802. ):
  1803. inferred_left = safe_infer(binop.left)
  1804. if isinstance(inferred_left, nodes.Const) and isinstance(
  1805. inferred_left.value, int
  1806. ):
  1807. return True, binop.op
  1808. return False, ""
  1809. return False, ""
  1810. def is_module_ignored(
  1811. module: nodes.Module,
  1812. ignored_modules: Iterable[str],
  1813. ) -> bool:
  1814. ignored_modules = set(ignored_modules)
  1815. module_name = module.name
  1816. module_qname = module.qname()
  1817. for ignore in ignored_modules:
  1818. # Try to match the module name / fully qualified name directly
  1819. if module_qname in ignored_modules or module_name in ignored_modules:
  1820. return True
  1821. # Try to see if the ignores pattern match against the module name.
  1822. if fnmatch.fnmatch(module_qname, ignore):
  1823. return True
  1824. # Otherwise, we might have a root module name being ignored,
  1825. # and the qualified owner has more levels of depth.
  1826. parts = deque(module_name.split("."))
  1827. current_module = ""
  1828. while parts:
  1829. part = parts.popleft()
  1830. if not current_module:
  1831. current_module = part
  1832. else:
  1833. current_module += f".{part}"
  1834. if current_module in ignored_modules:
  1835. return True
  1836. return False
  1837. def is_singleton_const(node: nodes.NodeNG) -> bool:
  1838. return isinstance(node, nodes.Const) and any(
  1839. node.value is value for value in SINGLETON_VALUES
  1840. )
  1841. def is_terminating_func(node: nodes.Call) -> bool:
  1842. """Detect call to exit(), quit(), os._exit(), or sys.exit()."""
  1843. if (
  1844. not isinstance(node.func, nodes.Attribute)
  1845. and not (isinstance(node.func, nodes.Name))
  1846. or isinstance(node.parent, nodes.Lambda)
  1847. ):
  1848. return False
  1849. try:
  1850. for inferred in node.func.infer():
  1851. if (
  1852. hasattr(inferred, "qname")
  1853. and inferred.qname() in TERMINATING_FUNCS_QNAMES
  1854. ):
  1855. return True
  1856. except (StopIteration, astroid.InferenceError):
  1857. pass
  1858. return False
  1859. def is_class_attr(name: str, klass: nodes.ClassDef) -> bool:
  1860. try:
  1861. klass.getattr(name)
  1862. return True
  1863. except astroid.NotFoundError:
  1864. return False
  1865. def is_defined(name: str, node: nodes.NodeNG) -> bool:
  1866. """Searches for a tree node that defines the given variable name."""
  1867. is_defined_so_far = False
  1868. if isinstance(node, nodes.NamedExpr):
  1869. is_defined_so_far = node.target.name == name
  1870. if isinstance(node, (nodes.Import, nodes.ImportFrom)):
  1871. is_defined_so_far = any(node_name[0] == name for node_name in node.names)
  1872. if isinstance(node, nodes.With):
  1873. is_defined_so_far = any(
  1874. isinstance(item[1], nodes.AssignName) and item[1].name == name
  1875. for item in node.items
  1876. )
  1877. if isinstance(node, (nodes.ClassDef, nodes.FunctionDef)):
  1878. is_defined_so_far = node.name == name
  1879. if isinstance(node, nodes.AnnAssign):
  1880. is_defined_so_far = (
  1881. node.value
  1882. and isinstance(node.target, nodes.AssignName)
  1883. and node.target.name == name
  1884. )
  1885. if isinstance(node, nodes.Assign):
  1886. is_defined_so_far = any(
  1887. any(
  1888. (
  1889. (
  1890. isinstance(elt, nodes.Starred)
  1891. and isinstance(elt.value, nodes.AssignName)
  1892. and elt.value.name == name
  1893. )
  1894. or (isinstance(elt, nodes.AssignName) and elt.name == name)
  1895. )
  1896. for elt in get_all_elements(target)
  1897. )
  1898. for target in node.targets
  1899. )
  1900. return is_defined_so_far or any(
  1901. is_defined(name, child) for child in node.get_children()
  1902. )
  1903. def get_inverse_comparator(op: str) -> str:
  1904. """Returns the inverse comparator given a comparator.
  1905. E.g. when given "==", returns "!="
  1906. :param str op: the comparator to look up.
  1907. :returns: The inverse of the comparator in string format
  1908. :raises KeyError: if input is not recognized as a comparator
  1909. """
  1910. return {
  1911. "==": "!=",
  1912. "!=": "==",
  1913. "<": ">=",
  1914. ">": "<=",
  1915. "<=": ">",
  1916. ">=": "<",
  1917. "in": "not in",
  1918. "not in": "in",
  1919. "is": "is not",
  1920. "is not": "is",
  1921. }[op]
  1922. def not_condition_as_string(
  1923. test_node: nodes.Compare | nodes.Name | nodes.UnaryOp | nodes.BoolOp | nodes.BinOp,
  1924. ) -> str:
  1925. msg = f"not {test_node.as_string()}"
  1926. if isinstance(test_node, nodes.UnaryOp):
  1927. msg = test_node.operand.as_string()
  1928. elif isinstance(test_node, nodes.BoolOp):
  1929. msg = f"not ({test_node.as_string()})"
  1930. elif isinstance(test_node, nodes.Compare):
  1931. lhs = test_node.left
  1932. ops, rhs = test_node.ops[0]
  1933. lower_priority_expressions = (
  1934. nodes.Lambda,
  1935. nodes.UnaryOp,
  1936. nodes.BoolOp,
  1937. nodes.IfExp,
  1938. nodes.NamedExpr,
  1939. )
  1940. lhs = (
  1941. f"({lhs.as_string()})"
  1942. if isinstance(lhs, lower_priority_expressions)
  1943. else lhs.as_string()
  1944. )
  1945. rhs = (
  1946. f"({rhs.as_string()})"
  1947. if isinstance(rhs, lower_priority_expressions)
  1948. else rhs.as_string()
  1949. )
  1950. msg = f"{lhs} {get_inverse_comparator(ops)} {rhs}"
  1951. return msg
  1952. def clear_lru_caches() -> None:
  1953. """Clear caches holding references to AST nodes."""
  1954. # pylint: disable-next=import-outside-toplevel
  1955. from pylint.checkers.variables import overridden_method
  1956. caches_holding_node_references: list[_lru_cache_wrapper[Any]] = [
  1957. in_for_else_branch,
  1958. infer_all,
  1959. is_overload_stub,
  1960. overridden_method,
  1961. unimplemented_abstract_methods,
  1962. safe_infer,
  1963. ]
  1964. for lru in caches_holding_node_references:
  1965. lru.cache_clear()