class_checker.py 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408
  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. """Classes checker for Python code."""
  5. from __future__ import annotations
  6. from collections import defaultdict
  7. from collections.abc import Callable, Sequence
  8. from functools import cached_property
  9. from itertools import chain, zip_longest
  10. from re import Pattern
  11. from typing import TYPE_CHECKING, Any, NamedTuple, TypeAlias
  12. import astroid
  13. import astroid.exceptions
  14. from astroid import bases, nodes, objects, util
  15. from astroid.typing import SuccessfulInferenceResult
  16. from pylint.checkers import BaseChecker, utils
  17. from pylint.checkers.utils import (
  18. PYMETHODS,
  19. class_is_abstract,
  20. decorated_with,
  21. decorated_with_property,
  22. get_outer_class,
  23. has_known_bases,
  24. is_attr_private,
  25. is_attr_protected,
  26. is_builtin_object,
  27. is_comprehension,
  28. is_iterable,
  29. is_property_setter,
  30. is_property_setter_or_deleter,
  31. node_frame_class,
  32. only_required_for_messages,
  33. safe_infer,
  34. unimplemented_abstract_methods,
  35. uninferable_final_decorators,
  36. )
  37. from pylint.interfaces import HIGH, INFERENCE
  38. from pylint.typing import MessageDefinitionTuple
  39. if TYPE_CHECKING:
  40. from pylint.lint.pylinter import PyLinter
  41. _AccessNodes: TypeAlias = nodes.Attribute | nodes.AssignAttr
  42. INVALID_BASE_CLASSES = {"bool", "range", "slice", "memoryview"}
  43. ALLOWED_PROPERTIES = {"bultins.property", "functools.cached_property"}
  44. BUILTIN_DECORATORS = {"builtins.property", "builtins.classmethod"}
  45. ASTROID_TYPE_COMPARATORS = {
  46. nodes.Const: lambda a, b: a.value == b.value,
  47. nodes.ClassDef: lambda a, b: a.qname == b.qname,
  48. nodes.Tuple: lambda a, b: a.elts == b.elts,
  49. nodes.List: lambda a, b: a.elts == b.elts,
  50. nodes.Dict: lambda a, b: a.items == b.items,
  51. nodes.Name: lambda a, b: set(a.infer()) == set(b.infer()),
  52. }
  53. # Dealing with useless override detection, with regard
  54. # to parameters vs arguments
  55. class _CallSignature(NamedTuple):
  56. args: list[str | None]
  57. kws: dict[str | None, str | None]
  58. starred_args: list[str]
  59. starred_kws: list[str]
  60. class _ParameterSignature(NamedTuple):
  61. args: list[str]
  62. kwonlyargs: list[str]
  63. varargs: str
  64. kwargs: str
  65. def _signature_from_call(call: nodes.Call) -> _CallSignature:
  66. kws = {}
  67. args = []
  68. starred_kws = []
  69. starred_args = []
  70. for keyword in call.keywords or []:
  71. arg, value = keyword.arg, keyword.value
  72. if arg is None and isinstance(value, nodes.Name):
  73. # Starred node, and we are interested only in names,
  74. # otherwise some transformation might occur for the parameter.
  75. starred_kws.append(value.name)
  76. elif isinstance(value, nodes.Name):
  77. kws[arg] = value.name
  78. else:
  79. kws[arg] = None
  80. for arg in call.args:
  81. match arg:
  82. case nodes.Starred(value=nodes.Name(name=name)):
  83. # Positional variadic and a name, otherwise some transformation
  84. # might have occurred.
  85. starred_args.append(name)
  86. case nodes.Name():
  87. args.append(arg.name)
  88. case _:
  89. args.append(None)
  90. return _CallSignature(args, kws, starred_args, starred_kws)
  91. def _signature_from_arguments(arguments: nodes.Arguments) -> _ParameterSignature:
  92. kwarg = arguments.kwarg
  93. vararg = arguments.vararg
  94. args = [
  95. arg.name
  96. for arg in chain(arguments.posonlyargs, arguments.args)
  97. if arg.name != "self"
  98. ]
  99. kwonlyargs = [arg.name for arg in arguments.kwonlyargs]
  100. return _ParameterSignature(args, kwonlyargs, vararg, kwarg)
  101. def _definition_equivalent_to_call(
  102. definition: _ParameterSignature, call: _CallSignature
  103. ) -> bool:
  104. """Check if a definition signature is equivalent to a call."""
  105. if definition.kwargs:
  106. if definition.kwargs not in call.starred_kws:
  107. return False
  108. elif call.starred_kws:
  109. return False
  110. if definition.varargs:
  111. if definition.varargs not in call.starred_args:
  112. return False
  113. elif call.starred_args:
  114. return False
  115. if any(kw not in call.kws for kw in definition.kwonlyargs):
  116. return False
  117. if definition.args != call.args:
  118. return False
  119. # No extra kwargs in call.
  120. return all(kw in call.args or kw in definition.kwonlyargs for kw in call.kws)
  121. def _is_trivial_super_delegation(function: nodes.FunctionDef) -> bool:
  122. """Check whether a function definition is a method consisting only of a
  123. call to the same function on the superclass.
  124. """
  125. if (
  126. not function.is_method()
  127. # Adding decorators to a function changes behavior and
  128. # constitutes a non-trivial change.
  129. or function.decorators
  130. ):
  131. return False
  132. body = function.body
  133. if len(body) != 1:
  134. # Multiple statements, which means this overridden method
  135. # could do multiple things we are not aware of.
  136. return False
  137. statement = body[0]
  138. if not isinstance(statement, (nodes.Expr, nodes.Return)):
  139. # Doing something else than what we are interested in.
  140. return False
  141. call = statement.value
  142. match call := statement.value:
  143. case nodes.Call(func=nodes.Attribute(expr=expr)):
  144. pass
  145. case _:
  146. # Not a super() attribute access.
  147. return False
  148. # Anything other than a super call is non-trivial.
  149. super_call = safe_infer(expr)
  150. if not isinstance(super_call, objects.Super):
  151. return False
  152. # The name should be the same.
  153. if call.func.attrname != function.name:
  154. return False
  155. # Should be a super call with the MRO pointer being the
  156. # current class and the type being the current instance.
  157. current_scope = function.parent.scope()
  158. if not (
  159. super_call.mro_pointer == current_scope
  160. and isinstance(super_call.type, astroid.Instance)
  161. and super_call.type.name == current_scope.name
  162. ):
  163. return False
  164. return True
  165. # Deal with parameters overriding in two methods.
  166. def _positional_parameters(method: nodes.FunctionDef) -> list[nodes.AssignName]:
  167. positional = method.args.args
  168. if method.is_bound() and method.type in {"classmethod", "method"}:
  169. positional = positional[1:]
  170. return positional # type: ignore[no-any-return]
  171. class _DefaultMissing:
  172. """Sentinel value for missing arg default, use _DEFAULT_MISSING."""
  173. _DEFAULT_MISSING = _DefaultMissing()
  174. def _has_different_parameters_default_value(
  175. original: nodes.Arguments, overridden: nodes.Arguments
  176. ) -> bool:
  177. """Check if original and overridden methods arguments have different default values.
  178. Return True if one of the overridden arguments has a default
  179. value different from the default value of the original argument
  180. If one of the method doesn't have argument (.args is None)
  181. return False
  182. """
  183. if original.args is None or overridden.args is None:
  184. return False
  185. for param in chain(original.args, original.kwonlyargs):
  186. try:
  187. original_default = original.default_value(param.name)
  188. except astroid.exceptions.NoDefault:
  189. original_default = _DEFAULT_MISSING
  190. try:
  191. overridden_default = overridden.default_value(param.name)
  192. if original_default is _DEFAULT_MISSING:
  193. # Only the original has a default.
  194. return True
  195. except astroid.exceptions.NoDefault:
  196. if original_default is _DEFAULT_MISSING:
  197. # Both have a default, no difference
  198. continue
  199. # Only the override has a default.
  200. return True
  201. original_type = type(original_default)
  202. if not isinstance(overridden_default, original_type):
  203. # Two args with same name but different types
  204. return True
  205. is_same_fn: Callable[[Any, Any], bool] | None = ASTROID_TYPE_COMPARATORS.get(
  206. original_type
  207. )
  208. if is_same_fn is None:
  209. # If the default value comparison is unhandled, assume the value is different
  210. return True
  211. if not is_same_fn(original_default, overridden_default):
  212. # Two args with same type but different values
  213. return True
  214. return False
  215. def _has_different_parameters(
  216. original: list[nodes.AssignName],
  217. overridden: list[nodes.AssignName],
  218. dummy_parameter_regex: Pattern[str],
  219. ) -> list[str]:
  220. result: list[str] = []
  221. zipped = zip_longest(original, overridden)
  222. for original_param, overridden_param in zipped:
  223. if not overridden_param:
  224. return ["Number of parameters "]
  225. if not original_param:
  226. try:
  227. overridden_param.parent.default_value(overridden_param.name)
  228. continue
  229. except astroid.NoDefault:
  230. return ["Number of parameters "]
  231. # check for the arguments' name
  232. names = [param.name for param in (original_param, overridden_param)]
  233. if any(dummy_parameter_regex.match(name) for name in names):
  234. continue
  235. if original_param.name != overridden_param.name:
  236. result.append(
  237. f"Parameter '{original_param.name}' has been renamed "
  238. f"to '{overridden_param.name}' in"
  239. )
  240. return result
  241. def _has_different_keyword_only_parameters(
  242. original: list[nodes.AssignName],
  243. overridden: list[nodes.AssignName],
  244. ) -> list[str]:
  245. """Determine if the two methods have different keyword only parameters."""
  246. original_names = [i.name for i in original]
  247. overridden_names = [i.name for i in overridden]
  248. if any(name not in overridden_names for name in original_names):
  249. return ["Number of parameters "]
  250. for name in overridden_names:
  251. if name in original_names:
  252. continue
  253. try:
  254. overridden[0].parent.default_value(name)
  255. except astroid.NoDefault:
  256. return ["Number of parameters "]
  257. return []
  258. def _different_parameters(
  259. original: nodes.FunctionDef,
  260. overridden: nodes.FunctionDef,
  261. dummy_parameter_regex: Pattern[str],
  262. ) -> list[str]:
  263. """Determine if the two methods have different parameters.
  264. They are considered to have different parameters if:
  265. * they have different positional parameters, including different names
  266. * one of the methods is having variadics, while the other is not
  267. * they have different keyword only parameters.
  268. """
  269. output_messages = []
  270. original_parameters = _positional_parameters(original)
  271. overridden_parameters = _positional_parameters(overridden)
  272. # Copy kwonlyargs list so that we don't affect later function linting
  273. original_kwonlyargs = original.args.kwonlyargs
  274. # Allow positional/keyword variadic in overridden to match against any
  275. # positional/keyword argument in original.
  276. # Keep any arguments that are found separately in overridden to satisfy
  277. # later tests
  278. if overridden.args.vararg:
  279. overridden_names = [v.name for v in overridden_parameters]
  280. original_parameters = [
  281. v for v in original_parameters if v.name in overridden_names
  282. ]
  283. if overridden.args.kwarg:
  284. overridden_names = [v.name for v in overridden.args.kwonlyargs]
  285. original_kwonlyargs = [
  286. v for v in original.args.kwonlyargs if v.name in overridden_names
  287. ]
  288. different_positional = _has_different_parameters(
  289. original_parameters, overridden_parameters, dummy_parameter_regex
  290. )
  291. different_kwonly = _has_different_keyword_only_parameters(
  292. original_kwonlyargs, overridden.args.kwonlyargs
  293. )
  294. if different_kwonly and different_positional:
  295. if "Number " in different_positional[0] and "Number " in different_kwonly[0]:
  296. output_messages.append("Number of parameters ")
  297. output_messages += different_positional[1:]
  298. output_messages += different_kwonly[1:]
  299. else:
  300. output_messages += different_positional
  301. output_messages += different_kwonly
  302. else:
  303. if different_positional:
  304. output_messages += different_positional
  305. if different_kwonly:
  306. output_messages += different_kwonly
  307. # Arguments will only violate LSP if there are variadics in the original
  308. # that are then removed from the overridden
  309. kwarg_lost = original.args.kwarg and not overridden.args.kwarg
  310. vararg_lost = original.args.vararg and not overridden.args.vararg
  311. if kwarg_lost or vararg_lost:
  312. output_messages += ["Variadics removed in"]
  313. if original.name in PYMETHODS:
  314. # Ignore the difference for special methods. If the parameter
  315. # numbers are different, then that is going to be caught by
  316. # unexpected-special-method-signature.
  317. # If the names are different, it doesn't matter, since they can't
  318. # be used as keyword arguments anyway.
  319. output_messages.clear()
  320. return output_messages
  321. def _is_invalid_base_class(cls: nodes.ClassDef) -> bool:
  322. return cls.name in INVALID_BASE_CLASSES and is_builtin_object(cls)
  323. def _has_data_descriptor(cls: nodes.ClassDef, attr: str) -> bool:
  324. attributes = cls.getattr(attr)
  325. for attribute in attributes:
  326. try:
  327. for inferred in attribute.infer():
  328. if isinstance(inferred, astroid.Instance):
  329. try:
  330. inferred.getattr("__get__")
  331. inferred.getattr("__set__")
  332. except astroid.NotFoundError:
  333. continue
  334. else:
  335. return True
  336. except astroid.InferenceError:
  337. # Can't infer, avoid emitting a false positive in this case.
  338. return True
  339. return False
  340. def _called_in_methods(
  341. func: nodes.LocalsDictNodeNG,
  342. klass: nodes.ClassDef,
  343. methods: Sequence[str],
  344. ) -> bool:
  345. """Check if the func was called in any of the given methods,
  346. belonging to the *klass*.
  347. Returns True if so, False otherwise.
  348. """
  349. if not isinstance(func, nodes.FunctionDef):
  350. return False
  351. for method in methods:
  352. try:
  353. inferred = klass.getattr(method)
  354. except astroid.NotFoundError:
  355. continue
  356. for infer_method in inferred:
  357. for call in infer_method.nodes_of_class(nodes.Call):
  358. try:
  359. bound = next(call.func.infer())
  360. except (astroid.InferenceError, StopIteration):
  361. continue
  362. if not isinstance(bound, astroid.BoundMethod):
  363. continue
  364. func_obj = bound._proxied
  365. if isinstance(func_obj, astroid.UnboundMethod):
  366. func_obj = func_obj._proxied
  367. if func_obj.name == func.name:
  368. return True
  369. return False
  370. def _is_attribute_property(name: str, klass: nodes.ClassDef) -> bool:
  371. """Check if the given attribute *name* is a property in the given *klass*.
  372. It will look for `property` calls or for functions
  373. with the given name, decorated by `property` or `property`
  374. subclasses.
  375. Returns ``True`` if the name is a property in the given klass,
  376. ``False`` otherwise.
  377. """
  378. try:
  379. attributes = klass.getattr(name)
  380. except astroid.NotFoundError:
  381. return False
  382. property_name = "builtins.property"
  383. for attr in attributes:
  384. if isinstance(attr, util.UninferableBase):
  385. continue
  386. try:
  387. inferred = next(attr.infer())
  388. except astroid.InferenceError:
  389. continue
  390. if isinstance(inferred, nodes.FunctionDef) and decorated_with_property(
  391. inferred
  392. ):
  393. return True
  394. if inferred.pytype() == property_name:
  395. return True
  396. return False
  397. def _has_same_layout_slots(
  398. slots: list[nodes.Const | None], assigned_value: nodes.Name
  399. ) -> bool:
  400. inferred = next(assigned_value.infer())
  401. if isinstance(inferred, nodes.ClassDef):
  402. other_slots = inferred.slots()
  403. if all(
  404. first_slot and second_slot and first_slot.value == second_slot.value
  405. for (first_slot, second_slot) in zip_longest(slots, other_slots)
  406. ):
  407. return True
  408. return False
  409. MSGS: dict[str, MessageDefinitionTuple] = {
  410. "F0202": (
  411. "Unable to check methods signature (%s / %s)",
  412. "method-check-failed",
  413. "Used when Pylint has been unable to check methods signature "
  414. "compatibility for an unexpected reason. Please report this kind "
  415. "if you don't make sense of it.",
  416. ),
  417. "E0202": (
  418. "An attribute defined in %s line %s hides this method",
  419. "method-hidden",
  420. "Used when a class defines a method which is hidden by an "
  421. "instance attribute from an ancestor class or set by some "
  422. "client code.",
  423. ),
  424. "E0203": (
  425. "Access to member %r before its definition line %s",
  426. "access-member-before-definition",
  427. "Used when an instance member is accessed before it's actually assigned.",
  428. ),
  429. "W0201": (
  430. "Attribute %r defined outside __init__",
  431. "attribute-defined-outside-init",
  432. "Used when an instance attribute is defined outside the __init__ method.",
  433. ),
  434. "W0212": (
  435. "Access to a protected member %s of a client class", # E0214
  436. "protected-access",
  437. "Used when a protected member (i.e. class member with a name "
  438. "beginning with an underscore) is accessed outside the class or a "
  439. "descendant of the class where it's defined.",
  440. ),
  441. "W0213": (
  442. "Flag member %(overlap)s shares bit positions with %(sources)s",
  443. "implicit-flag-alias",
  444. "Used when multiple integer values declared within an enum.IntFlag "
  445. "class share a common bit position.",
  446. ),
  447. "E0211": (
  448. "Method %r has no argument",
  449. "no-method-argument",
  450. "Used when a method which should have the bound instance as "
  451. "first argument has no argument defined.",
  452. ),
  453. "E0213": (
  454. 'Method %r should have "self" as first argument',
  455. "no-self-argument",
  456. 'Used when a method has an attribute different the "self" as '
  457. "first argument. This is considered as an error since this is "
  458. "a so common convention that you shouldn't break it!",
  459. ),
  460. "C0202": (
  461. "Class method %s should have %s as first argument",
  462. "bad-classmethod-argument",
  463. "Used when a class method has a first argument named differently "
  464. "than the value specified in valid-classmethod-first-arg option "
  465. '(default to "cls"), recommended to easily differentiate them '
  466. "from regular instance methods.",
  467. ),
  468. "C0203": (
  469. "Metaclass method %s should have %s as first argument",
  470. "bad-mcs-method-argument",
  471. "Used when a metaclass method has a first argument named "
  472. "differently than the value specified in valid-classmethod-first"
  473. '-arg option (default to "cls"), recommended to easily '
  474. "differentiate them from regular instance methods.",
  475. ),
  476. "C0204": (
  477. "Metaclass class method %s should have %s as first argument",
  478. "bad-mcs-classmethod-argument",
  479. "Used when a metaclass class method has a first argument named "
  480. "differently than the value specified in valid-metaclass-"
  481. 'classmethod-first-arg option (default to "mcs"), recommended to '
  482. "easily differentiate them from regular instance methods.",
  483. ),
  484. "W0211": (
  485. "Static method with %r as first argument",
  486. "bad-staticmethod-argument",
  487. 'Used when a static method has "self" or a value specified in '
  488. "valid-classmethod-first-arg option or "
  489. "valid-metaclass-classmethod-first-arg option as first argument.",
  490. ),
  491. "W0221": (
  492. "%s %s %r method",
  493. "arguments-differ",
  494. "Used when a method has a different number of arguments than in "
  495. "the implemented interface or in an overridden method. Extra arguments "
  496. "with default values are ignored.",
  497. ),
  498. "W0222": (
  499. "Signature differs from %s %r method",
  500. "signature-differs",
  501. "Used when a method signature is different than in the "
  502. "implemented interface or in an overridden method.",
  503. ),
  504. "W0223": (
  505. "Method %r is abstract in class %r but is not overridden in child class %r",
  506. "abstract-method",
  507. "Used when an abstract method (i.e. raise NotImplementedError) is "
  508. "not overridden in concrete class.",
  509. ),
  510. "W0231": (
  511. "__init__ method from base class %r is not called",
  512. "super-init-not-called",
  513. "Used when an ancestor class method has an __init__ method "
  514. "which is not called by a derived class.",
  515. ),
  516. "W0233": (
  517. "__init__ method from a non direct base class %r is called",
  518. "non-parent-init-called",
  519. "Used when an __init__ method is called on a class which is not "
  520. "in the direct ancestors for the analysed class.",
  521. ),
  522. "W0246": (
  523. "Useless parent or super() delegation in method %r",
  524. "useless-parent-delegation",
  525. "Used whenever we can detect that an overridden method is useless, "
  526. "relying on parent or super() delegation to do the same thing as another method "
  527. "from the MRO.",
  528. {"old_names": [("W0235", "useless-super-delegation")]},
  529. ),
  530. "W0236": (
  531. "Method %r was expected to be %r, found it instead as %r",
  532. "invalid-overridden-method",
  533. "Used when we detect that a method was overridden in a way "
  534. "that does not match its base class "
  535. "which could result in potential bugs at runtime.",
  536. ),
  537. "W0237": (
  538. "%s %s %r method",
  539. "arguments-renamed",
  540. "Used when a method parameter has a different name than in "
  541. "the implemented interface or in an overridden method.",
  542. ),
  543. "W0238": (
  544. "Unused private member `%s.%s`",
  545. "unused-private-member",
  546. "Emitted when a private member of a class is defined but not used.",
  547. ),
  548. "W0239": (
  549. "Method %r overrides a method decorated with typing.final which is defined in class %r",
  550. "overridden-final-method",
  551. "Used when a method decorated with typing.final has been overridden.",
  552. ),
  553. "W0240": (
  554. "Class %r is a subclass of a class decorated with typing.final: %r",
  555. "subclassed-final-class",
  556. "Used when a class decorated with typing.final has been subclassed.",
  557. ),
  558. "W0244": (
  559. "Redefined slots %r in subclass",
  560. "redefined-slots-in-subclass",
  561. "Used when a slot is re-defined in a subclass.",
  562. ),
  563. "W0245": (
  564. "Super call without brackets",
  565. "super-without-brackets",
  566. "Used when a call to super does not have brackets and thus is not an actual "
  567. "call and does not work as expected.",
  568. ),
  569. "E0236": (
  570. "Invalid object %r in __slots__, must contain only non empty strings",
  571. "invalid-slots-object",
  572. "Used when an invalid (non-string) object occurs in __slots__.",
  573. ),
  574. "E0237": (
  575. "Assigning to attribute %r not defined in class slots",
  576. "assigning-non-slot",
  577. "Used when assigning to an attribute not defined in the class slots.",
  578. ),
  579. "E0238": (
  580. "Invalid __slots__ object",
  581. "invalid-slots",
  582. "Used when an invalid __slots__ is found in class. "
  583. "Only a string, an iterable or a sequence is permitted.",
  584. ),
  585. "E0239": (
  586. "Inheriting %r, which is not a class.",
  587. "inherit-non-class",
  588. "Used when a class inherits from something which is not a class.",
  589. ),
  590. "E0240": (
  591. "Inconsistent method resolution order for class %r",
  592. "inconsistent-mro",
  593. "Used when a class has an inconsistent method resolution order.",
  594. ),
  595. "E0241": (
  596. "Duplicate bases for class %r",
  597. "duplicate-bases",
  598. "Duplicate use of base classes in derived classes raise TypeErrors.",
  599. ),
  600. "E0242": (
  601. "Value %r in slots conflicts with class variable",
  602. "class-variable-slots-conflict",
  603. "Used when a value in __slots__ conflicts with a class variable, property or method.",
  604. ),
  605. "E0243": (
  606. "Invalid assignment to '__class__'. Should be a class definition but got a '%s'",
  607. "invalid-class-object",
  608. "Used when an invalid object is assigned to a __class__ property. "
  609. "Only a class is permitted.",
  610. ),
  611. "E0244": (
  612. 'Extending inherited Enum class "%s"',
  613. "invalid-enum-extension",
  614. "Used when a class tries to extend an inherited Enum class. "
  615. "Doing so will raise a TypeError at runtime.",
  616. ),
  617. "E0245": (
  618. "No such name %r in __slots__",
  619. "declare-non-slot",
  620. "Raised when a type annotation on a class is absent from the list of names in __slots__, "
  621. "and __slots__ does not contain a __dict__ entry.",
  622. ),
  623. "R0202": (
  624. "Consider using a decorator instead of calling classmethod",
  625. "no-classmethod-decorator",
  626. "Used when a class method is defined without using the decorator syntax.",
  627. ),
  628. "R0203": (
  629. "Consider using a decorator instead of calling staticmethod",
  630. "no-staticmethod-decorator",
  631. "Used when a static method is defined without using the decorator syntax.",
  632. ),
  633. "C0205": (
  634. "Class __slots__ should be a non-string iterable",
  635. "single-string-used-for-slots",
  636. "Used when a class __slots__ is a simple string, rather than an iterable.",
  637. ),
  638. "R0205": (
  639. "Class %r inherits from object, can be safely removed from bases in python3",
  640. "useless-object-inheritance",
  641. "Used when a class inherit from object, which under python3 is implicit, "
  642. "hence can be safely removed from bases.",
  643. ),
  644. "R0206": (
  645. "Cannot have defined parameters for properties",
  646. "property-with-parameters",
  647. "Used when we detect that a property also has parameters, which are useless, "
  648. "given that properties cannot be called with additional arguments.",
  649. ),
  650. }
  651. def _scope_default() -> defaultdict[str, list[_AccessNodes]]:
  652. # It's impossible to nest defaultdicts so we must use a function
  653. return defaultdict(list)
  654. class ScopeAccessMap:
  655. """Store the accessed variables per scope."""
  656. def __init__(self) -> None:
  657. self._scopes: defaultdict[
  658. nodes.ClassDef, defaultdict[str, list[_AccessNodes]]
  659. ] = defaultdict(_scope_default)
  660. def set_accessed(self, node: _AccessNodes) -> None:
  661. """Set the given node as accessed."""
  662. frame = node_frame_class(node)
  663. if frame is None:
  664. # The node does not live in a class.
  665. return
  666. self._scopes[frame][node.attrname].append(node)
  667. def accessed(self, scope: nodes.ClassDef) -> dict[str, list[_AccessNodes]]:
  668. """Get the accessed variables for the given scope."""
  669. return self._scopes.get(scope, {})
  670. class ClassChecker(BaseChecker):
  671. """Checker for class nodes.
  672. Checks for :
  673. * methods without self as first argument
  674. * overridden methods signature
  675. * access only to existent members via self
  676. * attributes not defined in the __init__ method
  677. * unreachable code
  678. """
  679. # configuration section name
  680. name = "classes"
  681. # messages
  682. msgs = MSGS
  683. # configuration options
  684. options = (
  685. (
  686. "defining-attr-methods",
  687. {
  688. "default": (
  689. "__init__",
  690. "__new__",
  691. "setUp",
  692. "asyncSetUp",
  693. "__post_init__",
  694. ),
  695. "type": "csv",
  696. "metavar": "<method names>",
  697. "help": "List of method names used to declare (i.e. assign) \
  698. instance attributes.",
  699. },
  700. ),
  701. (
  702. "valid-classmethod-first-arg",
  703. {
  704. "default": ("cls",),
  705. "type": "csv",
  706. "metavar": "<argument names>",
  707. "help": "List of valid names for the first argument in \
  708. a class method.",
  709. },
  710. ),
  711. (
  712. "valid-metaclass-classmethod-first-arg",
  713. {
  714. "default": ("mcs",),
  715. "type": "csv",
  716. "metavar": "<argument names>",
  717. "help": "List of valid names for the first argument in \
  718. a metaclass class method.",
  719. },
  720. ),
  721. (
  722. "exclude-protected",
  723. {
  724. "default": (
  725. # namedtuple public API.
  726. "_asdict",
  727. "_fields",
  728. "_replace",
  729. "_source",
  730. "_make",
  731. "os._exit",
  732. ),
  733. "type": "csv",
  734. "metavar": "<protected access exclusions>",
  735. "help": (
  736. "List of member names, which should be excluded "
  737. "from the protected access warning."
  738. ),
  739. },
  740. ),
  741. (
  742. "check-protected-access-in-special-methods",
  743. {
  744. "default": False,
  745. "type": "yn",
  746. "metavar": "<y or n>",
  747. "help": "Warn about protected attribute access inside special methods",
  748. },
  749. ),
  750. )
  751. def __init__(self, linter: PyLinter) -> None:
  752. super().__init__(linter)
  753. self._accessed = ScopeAccessMap()
  754. self._first_attrs: list[str | None] = []
  755. def open(self) -> None:
  756. self._mixin_class_rgx = self.linter.config.mixin_class_rgx
  757. py_version = self.linter.config.py_version
  758. self._py38_plus = py_version >= (3, 8)
  759. @cached_property
  760. def _dummy_rgx(self) -> Pattern[str]:
  761. return self.linter.config.dummy_variables_rgx # type: ignore[no-any-return]
  762. @only_required_for_messages(
  763. "abstract-method",
  764. "invalid-slots",
  765. "single-string-used-for-slots",
  766. "invalid-slots-object",
  767. "class-variable-slots-conflict",
  768. "inherit-non-class",
  769. "useless-object-inheritance",
  770. "inconsistent-mro",
  771. "duplicate-bases",
  772. "redefined-slots-in-subclass",
  773. "invalid-enum-extension",
  774. "subclassed-final-class",
  775. "implicit-flag-alias",
  776. "declare-non-slot",
  777. )
  778. def visit_classdef(self, node: nodes.ClassDef) -> None:
  779. """Init visit variable _accessed."""
  780. self._check_bases_classes(node)
  781. self._check_slots(node)
  782. self._check_proper_bases(node)
  783. self._check_typing_final(node)
  784. self._check_consistent_mro(node)
  785. self._check_declare_non_slot(node)
  786. def _check_declare_non_slot(self, node: nodes.ClassDef) -> None:
  787. if not self._has_valid_slots(node):
  788. return
  789. slot_names = self._get_classdef_slots_names(node)
  790. # Stop if empty __slots__ in the class body, this likely indicates that
  791. # this class takes part in multiple inheritance with other slotted classes.
  792. if not slot_names:
  793. return
  794. # Stop if we find __dict__, since this means attributes can be set
  795. # dynamically
  796. if "__dict__" in slot_names:
  797. return
  798. for base in node.bases:
  799. ancestor = safe_infer(base)
  800. if not isinstance(ancestor, nodes.ClassDef):
  801. continue
  802. # if any base doesn't have __slots__, attributes can be set dynamically, so stop
  803. if not self._has_valid_slots(ancestor):
  804. return
  805. for slot_name in self._get_classdef_slots_names(ancestor):
  806. if slot_name == "__dict__":
  807. return
  808. slot_names.append(slot_name)
  809. # Every class in bases has __slots__, our __slots__ is non-empty and there is no __dict__
  810. for child in node.body:
  811. match child:
  812. case nodes.AnnAssign(
  813. target=nodes.AssignName(name=name), value=None
  814. ) if (name not in slot_names):
  815. self.add_message(
  816. "declare-non-slot",
  817. args=child.target.name,
  818. node=child.target,
  819. confidence=INFERENCE,
  820. )
  821. def _check_consistent_mro(self, node: nodes.ClassDef) -> None:
  822. """Detect that a class has a consistent mro or duplicate bases."""
  823. try:
  824. node.mro()
  825. except astroid.InconsistentMroError:
  826. self.add_message("inconsistent-mro", args=node.name, node=node)
  827. except astroid.DuplicateBasesError:
  828. self.add_message("duplicate-bases", args=node.name, node=node)
  829. def _check_enum_base(self, node: nodes.ClassDef, ancestor: nodes.ClassDef) -> None:
  830. match ancestor.getattr("__members__"):
  831. case [nodes.Dict(items=items), *_] if items:
  832. for _, name_node in items:
  833. # Exempt type annotations without value assignments
  834. if all(
  835. isinstance(item.parent, nodes.AnnAssign)
  836. and item.parent.value is None
  837. for item in ancestor.getattr(name_node.name)
  838. ):
  839. continue
  840. self.add_message(
  841. "invalid-enum-extension",
  842. args=ancestor.name,
  843. node=node,
  844. confidence=INFERENCE,
  845. )
  846. break
  847. if ancestor.is_subtype_of("enum.IntFlag"):
  848. # Collect integer flag assignments present on the class
  849. assignments = defaultdict(list)
  850. for assign_name in node.nodes_of_class(nodes.AssignName):
  851. match assign_name.parent:
  852. case nodes.Assign(value=object(value=int() as value)):
  853. assignments[value].append(assign_name)
  854. # For each bit position, collect all the flags that set the bit
  855. bit_flags = defaultdict(set)
  856. for flag in assignments:
  857. flag_bits = (i for i, c in enumerate(reversed(bin(flag))) if c == "1")
  858. for bit in flag_bits:
  859. bit_flags[bit].add(flag)
  860. # Collect the minimum, unique values that each flag overlaps with
  861. overlaps = defaultdict(list)
  862. for flags in bit_flags.values():
  863. source, *conflicts = sorted(flags)
  864. for conflict in conflicts:
  865. overlaps[conflict].append(source)
  866. # Report the overlapping values
  867. for overlap in overlaps:
  868. for assignment_node in assignments[overlap]:
  869. self.add_message(
  870. "implicit-flag-alias",
  871. node=assignment_node,
  872. args={
  873. "overlap": f"<{node.name}.{assignment_node.name}: {overlap}>",
  874. "sources": ", ".join(
  875. f"<{node.name}.{assignments[source][0].name}: {source}> "
  876. f"({overlap} & {source} = {overlap & source})"
  877. for source in overlaps[overlap]
  878. ),
  879. },
  880. confidence=INFERENCE,
  881. )
  882. def _check_proper_bases(self, node: nodes.ClassDef) -> None:
  883. """Detect that a class inherits something which is not
  884. a class or a type.
  885. """
  886. for base in node.bases:
  887. ancestor = safe_infer(base)
  888. if not ancestor:
  889. continue
  890. if isinstance(ancestor, astroid.Instance) and (
  891. ancestor.is_subtype_of("builtins.type")
  892. or ancestor.is_subtype_of(".Protocol")
  893. ):
  894. continue
  895. if not isinstance(ancestor, nodes.ClassDef) or _is_invalid_base_class(
  896. ancestor
  897. ):
  898. self.add_message("inherit-non-class", args=base.as_string(), node=node)
  899. if isinstance(ancestor, nodes.ClassDef) and ancestor.is_subtype_of(
  900. "enum.Enum"
  901. ):
  902. self._check_enum_base(node, ancestor)
  903. if ancestor.name == object.__name__:
  904. self.add_message(
  905. "useless-object-inheritance", args=node.name, node=node
  906. )
  907. def _check_typing_final(self, node: nodes.ClassDef) -> None:
  908. """Detect that a class does not subclass a class decorated with
  909. `typing.final`.
  910. """
  911. if not self._py38_plus:
  912. return
  913. for base in node.bases:
  914. ancestor = safe_infer(base)
  915. if not ancestor:
  916. continue
  917. if isinstance(ancestor, nodes.ClassDef) and (
  918. decorated_with(ancestor, ["typing.final"])
  919. or uninferable_final_decorators(ancestor.decorators)
  920. ):
  921. self.add_message(
  922. "subclassed-final-class",
  923. args=(node.name, ancestor.name),
  924. node=node,
  925. )
  926. @only_required_for_messages(
  927. "unused-private-member",
  928. "attribute-defined-outside-init",
  929. "access-member-before-definition",
  930. )
  931. def leave_classdef(self, node: nodes.ClassDef) -> None:
  932. """Checker for Class nodes.
  933. check that instance attributes are defined in __init__ and check
  934. access to existent members
  935. """
  936. self._check_unused_private_functions(node)
  937. self._check_unused_private_variables(node)
  938. self._check_unused_private_attributes(node)
  939. self._check_attribute_defined_outside_init(node)
  940. def _check_unused_private_functions(self, node: nodes.ClassDef) -> None:
  941. for function_def in node.nodes_of_class(nodes.FunctionDef):
  942. if not is_attr_private(function_def.name):
  943. continue
  944. parent_scope = function_def.parent.scope()
  945. if isinstance(parent_scope, nodes.FunctionDef):
  946. # Handle nested functions
  947. if function_def.name in (
  948. n.name for n in parent_scope.nodes_of_class(nodes.Name)
  949. ):
  950. continue
  951. for child in node.nodes_of_class((nodes.Name, nodes.Attribute)):
  952. # Check for cases where the functions are used as a variable instead of as a
  953. # method call
  954. if isinstance(child, nodes.Name) and child.name == function_def.name:
  955. break
  956. if isinstance(child, nodes.Attribute):
  957. # Ignore recursive calls
  958. if (
  959. child.attrname != function_def.name
  960. or child.scope() == function_def
  961. ):
  962. continue
  963. # Check self.__attrname, cls.__attrname, node_name.__attrname
  964. if isinstance(child.expr, nodes.Name) and child.expr.name in {
  965. "self",
  966. "cls",
  967. node.name,
  968. }:
  969. break
  970. # Check type(self).__attrname
  971. if isinstance(child.expr, nodes.Call):
  972. inferred = safe_infer(child.expr)
  973. if (
  974. isinstance(inferred, nodes.ClassDef)
  975. and inferred.name == node.name
  976. ):
  977. break
  978. else:
  979. name_stack = []
  980. curr = parent_scope
  981. # Generate proper names for nested functions
  982. while curr != node:
  983. name_stack.append(curr.name)
  984. curr = curr.parent.scope()
  985. outer_level_names = f"{'.'.join(reversed(name_stack))}"
  986. function_repr = f"{outer_level_names}.{function_def.name}({function_def.args.as_string()})"
  987. self.add_message(
  988. "unused-private-member",
  989. node=function_def,
  990. args=(node.name, function_repr.lstrip(".")),
  991. )
  992. def _check_unused_private_variables(self, node: nodes.ClassDef) -> None:
  993. """Check if private variables are never used within a class."""
  994. for assign_name in node.nodes_of_class(nodes.AssignName):
  995. if isinstance(assign_name.parent, nodes.Arguments):
  996. continue # Ignore function arguments
  997. if not is_attr_private(assign_name.name):
  998. continue
  999. for child in node.nodes_of_class((nodes.Name, nodes.Attribute)):
  1000. if isinstance(child, nodes.Name) and child.name == assign_name.name:
  1001. break
  1002. if isinstance(child, nodes.Attribute):
  1003. if not isinstance(child.expr, nodes.Name):
  1004. break
  1005. if child.attrname == assign_name.name and child.expr.name in (
  1006. "self",
  1007. "cls",
  1008. node.name,
  1009. ):
  1010. break
  1011. else:
  1012. args = (node.name, assign_name.name)
  1013. self.add_message("unused-private-member", node=assign_name, args=args)
  1014. def _check_unused_private_attributes(self, node: nodes.ClassDef) -> None:
  1015. for assign_attr in node.nodes_of_class(nodes.AssignAttr):
  1016. if not (
  1017. is_attr_private(assign_attr.attrname)
  1018. and isinstance(assign_attr.expr, nodes.Name)
  1019. ):
  1020. continue
  1021. # Logic for checking false positive when using __new__,
  1022. # Get the returned object names of the __new__ magic function
  1023. # Then check if the attribute was consumed in other instance methods
  1024. acceptable_obj_names: list[str] = ["self"]
  1025. scope = assign_attr.scope()
  1026. if isinstance(scope, nodes.FunctionDef) and scope.name == "__new__":
  1027. acceptable_obj_names.extend(
  1028. [
  1029. return_node.value.name
  1030. for return_node in scope.nodes_of_class(nodes.Return)
  1031. if isinstance(return_node.value, nodes.Name)
  1032. ]
  1033. )
  1034. for attribute in node.nodes_of_class(nodes.Attribute):
  1035. if attribute.attrname != assign_attr.attrname:
  1036. continue
  1037. if not isinstance(attribute.expr, nodes.Name):
  1038. continue
  1039. if assign_attr.expr.name in {
  1040. "cls",
  1041. node.name,
  1042. } and attribute.expr.name in {"cls", "self", node.name}:
  1043. # If assigned to cls or class name, can be accessed by cls/self/class name
  1044. break
  1045. if (
  1046. assign_attr.expr.name in acceptable_obj_names
  1047. and attribute.expr.name == "self"
  1048. ):
  1049. # If assigned to self.attrib, can only be accessed by self
  1050. # Or if __new__ was used, the returned object names are acceptable
  1051. break
  1052. if assign_attr.expr.name == attribute.expr.name == node.name:
  1053. # Recognise attributes which are accessed via the class name
  1054. break
  1055. else:
  1056. args = (node.name, assign_attr.attrname)
  1057. self.add_message("unused-private-member", node=assign_attr, args=args)
  1058. def _check_attribute_defined_outside_init(self, cnode: nodes.ClassDef) -> None:
  1059. # check access to existent members on non metaclass classes
  1060. if (
  1061. "attribute-defined-outside-init"
  1062. in self.linter.config.ignored_checks_for_mixins
  1063. and self._mixin_class_rgx.match(cnode.name)
  1064. ):
  1065. # We are in a mixin class. No need to try to figure out if
  1066. # something is missing, since it is most likely that it will
  1067. # miss.
  1068. return
  1069. accessed = self._accessed.accessed(cnode)
  1070. if cnode.type != "metaclass":
  1071. self._check_accessed_members(cnode, accessed)
  1072. # checks attributes are defined in an allowed method such as __init__
  1073. if not self.linter.is_message_enabled("attribute-defined-outside-init"):
  1074. return
  1075. defining_methods = self.linter.config.defining_attr_methods
  1076. current_module = cnode.root()
  1077. for attr, nodes_lst in cnode.instance_attrs.items():
  1078. # Exclude `__dict__` as it is already defined.
  1079. if attr == "__dict__":
  1080. continue
  1081. # Skip nodes which are not in the current module and it may screw up
  1082. # the output, while it's not worth it
  1083. nodes_lst = [
  1084. n
  1085. for n in nodes_lst
  1086. if not isinstance(n.statement(), (nodes.Delete, nodes.AugAssign))
  1087. and n.root() is current_module
  1088. ]
  1089. if not nodes_lst:
  1090. continue # error detected by typechecking
  1091. # Check if any method attr is defined in is a defining method
  1092. # or if we have the attribute defined in a setter.
  1093. frames = (node.frame() for node in nodes_lst)
  1094. if any(
  1095. frame.name in defining_methods or is_property_setter(frame)
  1096. for frame in frames
  1097. ):
  1098. continue
  1099. # check attribute is defined in a parent's __init__
  1100. for parent in cnode.instance_attr_ancestors(attr):
  1101. attr_defined = False
  1102. # check if any parent method attr is defined in is a defining method
  1103. for node in parent.instance_attrs[attr]:
  1104. if node.frame().name in defining_methods:
  1105. attr_defined = True
  1106. if attr_defined:
  1107. # we're done :)
  1108. break
  1109. else:
  1110. # check attribute is defined as a class attribute
  1111. try:
  1112. cnode.local_attr(attr)
  1113. except astroid.NotFoundError:
  1114. for node in nodes_lst:
  1115. if node.frame().name not in defining_methods:
  1116. # If the attribute was set by a call in any
  1117. # of the defining methods, then don't emit
  1118. # the warning.
  1119. if _called_in_methods(
  1120. node.frame(), cnode, defining_methods
  1121. ):
  1122. continue
  1123. self.add_message(
  1124. "attribute-defined-outside-init", args=attr, node=node
  1125. )
  1126. # pylint: disable = too-many-branches
  1127. def visit_functiondef(self, node: nodes.FunctionDef) -> None:
  1128. """Check method arguments, overriding."""
  1129. # ignore actual functions
  1130. if not node.is_method():
  1131. return
  1132. self._check_useless_super_delegation(node)
  1133. self._check_property_with_parameters(node)
  1134. # 'is_method()' is called and makes sure that this is a 'nodes.ClassDef'
  1135. klass: nodes.ClassDef = node.parent.frame()
  1136. # check first argument is self if this is actually a method
  1137. self._check_first_arg_for_type(node, klass.type == "metaclass")
  1138. if node.name == "__init__":
  1139. self._check_init(node, klass)
  1140. return
  1141. # check signature if the method overloads inherited method
  1142. for overridden in klass.local_attr_ancestors(node.name):
  1143. # get astroid for the searched method
  1144. try:
  1145. parent_function = overridden[node.name]
  1146. except KeyError:
  1147. # we have found the method but it's not in the local
  1148. # dictionary.
  1149. # This may happen with astroid build from living objects
  1150. continue
  1151. if not isinstance(parent_function, nodes.FunctionDef):
  1152. continue
  1153. self._check_signature(node, parent_function, klass)
  1154. self._check_invalid_overridden_method(node, parent_function)
  1155. break
  1156. if node.decorators:
  1157. for decorator in node.decorators.nodes:
  1158. match decorator:
  1159. case nodes.Attribute(attrname="getter" | "setter" | "deleter"):
  1160. # attribute affectation will call this method, not hiding it
  1161. return
  1162. case nodes.Name():
  1163. if decorator.name in ALLOWED_PROPERTIES:
  1164. # attribute affectation will either call a setter or raise
  1165. # an attribute error, anyway not hiding the function
  1166. return
  1167. case nodes.Attribute():
  1168. if self._check_functools_or_not(decorator):
  1169. return
  1170. # Infer the decorator and see if it returns something useful
  1171. inferred = safe_infer(decorator)
  1172. if not inferred:
  1173. return
  1174. if isinstance(inferred, nodes.FunctionDef):
  1175. # Okay, it's a decorator, let's see what it can infer.
  1176. try:
  1177. inferred = next(inferred.infer_call_result(inferred))
  1178. except astroid.InferenceError:
  1179. return
  1180. try:
  1181. if (
  1182. isinstance(inferred, (astroid.Instance, nodes.ClassDef))
  1183. and inferred.getattr("__get__")
  1184. and inferred.getattr("__set__")
  1185. ):
  1186. return
  1187. except astroid.AttributeInferenceError:
  1188. pass
  1189. # check if the method is hidden by an attribute
  1190. # pylint: disable = too-many-try-statements
  1191. try:
  1192. overridden = klass.instance_attr(node.name)[0]
  1193. overridden_frame = overridden.frame()
  1194. match overridden_frame:
  1195. case nodes.FunctionDef(type="method"):
  1196. overridden_frame = overridden_frame.parent.frame()
  1197. if not (
  1198. isinstance(overridden_frame, nodes.ClassDef)
  1199. and klass.is_subtype_of(overridden_frame.qname())
  1200. ):
  1201. return
  1202. # If a subclass defined the method then it's not our fault.
  1203. for ancestor in klass.ancestors():
  1204. if node.name in ancestor.instance_attrs and is_attr_private(node.name):
  1205. return
  1206. for obj in ancestor.lookup(node.name)[1]:
  1207. if isinstance(obj, nodes.FunctionDef):
  1208. return
  1209. args = (overridden.root().name, overridden.fromlineno)
  1210. self.add_message("method-hidden", args=args, node=node)
  1211. except astroid.NotFoundError:
  1212. pass
  1213. visit_asyncfunctiondef = visit_functiondef
  1214. def _check_useless_super_delegation(self, function: nodes.FunctionDef) -> None:
  1215. """Check if the given function node is an useless method override.
  1216. We consider it *useless* if it uses the super() builtin, but having
  1217. nothing additional whatsoever than not implementing the method at all.
  1218. If the method uses super() to delegate an operation to the rest of the MRO,
  1219. and if the method called is the same as the current one, the arguments
  1220. passed to super() are the same as the parameters that were passed to
  1221. this method, then the method could be removed altogether, by letting
  1222. other implementation to take precedence.
  1223. """
  1224. if not _is_trivial_super_delegation(function):
  1225. return
  1226. call: nodes.Call = function.body[0].value
  1227. # Classes that override __eq__ should also override
  1228. # __hash__, even a trivial override is meaningful
  1229. if function.name == "__hash__":
  1230. for other_method in function.parent.mymethods():
  1231. if other_method.name == "__eq__":
  1232. return
  1233. # Check values of default args
  1234. klass = function.parent.frame()
  1235. meth_node = None
  1236. for overridden in klass.local_attr_ancestors(function.name):
  1237. # get astroid for the searched method
  1238. try:
  1239. meth_node = overridden[function.name]
  1240. except KeyError:
  1241. # we have found the method but it's not in the local
  1242. # dictionary.
  1243. # This may happen with astroid build from living objects
  1244. continue
  1245. if (
  1246. not isinstance(meth_node, nodes.FunctionDef)
  1247. # If the method have an ancestor which is not a
  1248. # function then it is legitimate to redefine it
  1249. or _has_different_parameters_default_value(
  1250. meth_node.args, function.args
  1251. )
  1252. # arguments to builtins such as Exception.__init__() cannot be inspected
  1253. or (meth_node.args.args is None and function.argnames() != ["self"])
  1254. ):
  1255. return
  1256. break
  1257. # Detect if the parameters are the same as the call's arguments.
  1258. params = _signature_from_arguments(function.args)
  1259. args = _signature_from_call(call)
  1260. if meth_node is not None:
  1261. # Detect if the super method uses varargs and the function doesn't or makes some of those explicit
  1262. if meth_node.args.vararg and (
  1263. not function.args.vararg
  1264. or len(function.args.args) > len(meth_node.args.args)
  1265. ):
  1266. return
  1267. def form_annotations(arguments: nodes.Arguments) -> list[str]:
  1268. annotations = chain(
  1269. (arguments.posonlyargs_annotations or []), arguments.annotations
  1270. )
  1271. return [ann.as_string() for ann in annotations if ann is not None]
  1272. called_annotations = form_annotations(function.args)
  1273. overridden_annotations = form_annotations(meth_node.args)
  1274. if called_annotations and overridden_annotations:
  1275. if called_annotations != overridden_annotations:
  1276. return
  1277. if (
  1278. function.returns is not None
  1279. and meth_node.returns is not None
  1280. and meth_node.returns.as_string() != function.returns.as_string()
  1281. ):
  1282. # Override adds typing information to the return type
  1283. return
  1284. if _definition_equivalent_to_call(params, args):
  1285. self.add_message(
  1286. "useless-parent-delegation",
  1287. node=function,
  1288. args=(function.name,),
  1289. confidence=INFERENCE,
  1290. )
  1291. def _check_property_with_parameters(self, node: nodes.FunctionDef) -> None:
  1292. if (
  1293. len(node.args.arguments) > 1
  1294. and decorated_with_property(node)
  1295. and not is_property_setter(node)
  1296. ):
  1297. self.add_message("property-with-parameters", node=node, confidence=HIGH)
  1298. def _check_invalid_overridden_method(
  1299. self,
  1300. function_node: nodes.FunctionDef,
  1301. parent_function_node: nodes.FunctionDef,
  1302. ) -> None:
  1303. parent_is_property = decorated_with_property(
  1304. parent_function_node
  1305. ) or is_property_setter_or_deleter(parent_function_node)
  1306. current_is_property = decorated_with_property(
  1307. function_node
  1308. ) or is_property_setter_or_deleter(function_node)
  1309. if parent_is_property and not current_is_property:
  1310. self.add_message(
  1311. "invalid-overridden-method",
  1312. args=(function_node.name, "property", function_node.type),
  1313. node=function_node,
  1314. )
  1315. elif not parent_is_property and current_is_property:
  1316. self.add_message(
  1317. "invalid-overridden-method",
  1318. args=(function_node.name, "method", "property"),
  1319. node=function_node,
  1320. )
  1321. parent_is_async = isinstance(parent_function_node, nodes.AsyncFunctionDef)
  1322. current_is_async = isinstance(function_node, nodes.AsyncFunctionDef)
  1323. if parent_is_async and not current_is_async:
  1324. self.add_message(
  1325. "invalid-overridden-method",
  1326. args=(function_node.name, "async", "non-async"),
  1327. node=function_node,
  1328. )
  1329. elif not parent_is_async and current_is_async:
  1330. self.add_message(
  1331. "invalid-overridden-method",
  1332. args=(function_node.name, "non-async", "async"),
  1333. node=function_node,
  1334. )
  1335. if (
  1336. decorated_with(parent_function_node, ["typing.final"])
  1337. or uninferable_final_decorators(parent_function_node.decorators)
  1338. ) and self._py38_plus:
  1339. self.add_message(
  1340. "overridden-final-method",
  1341. args=(function_node.name, parent_function_node.parent.frame().name),
  1342. node=function_node,
  1343. )
  1344. def _check_functools_or_not(self, decorator: nodes.Attribute) -> bool:
  1345. if decorator.attrname != "cached_property":
  1346. return False
  1347. if not isinstance(decorator.expr, nodes.Name):
  1348. return False
  1349. _, import_nodes = decorator.expr.lookup(decorator.expr.name)
  1350. if not import_nodes:
  1351. return False
  1352. import_node = import_nodes[0]
  1353. if not isinstance(import_node, (nodes.Import, nodes.ImportFrom)):
  1354. return False
  1355. return "functools" in dict(import_node.names)
  1356. def _has_valid_slots(self, node: nodes.ClassDef) -> bool:
  1357. if "__slots__" not in node.locals:
  1358. return False
  1359. try:
  1360. inferred_slots = tuple(node.ilookup("__slots__"))
  1361. except astroid.InferenceError:
  1362. return False
  1363. for slots in inferred_slots:
  1364. # check if __slots__ is a valid type
  1365. if isinstance(slots, util.UninferableBase):
  1366. return False
  1367. if not is_iterable(slots) and not is_comprehension(slots):
  1368. return False
  1369. if isinstance(slots, nodes.Const):
  1370. return False
  1371. if not hasattr(slots, "itered"):
  1372. # we can't obtain the values, maybe a .deque?
  1373. return False
  1374. return True
  1375. def _check_slots(self, node: nodes.ClassDef) -> None:
  1376. if "__slots__" not in node.locals:
  1377. return
  1378. try:
  1379. inferred_slots = tuple(node.ilookup("__slots__"))
  1380. except astroid.InferenceError:
  1381. return
  1382. for slots in inferred_slots:
  1383. # check if __slots__ is a valid type
  1384. if isinstance(slots, util.UninferableBase):
  1385. continue
  1386. if not is_iterable(slots) and not is_comprehension(slots):
  1387. self.add_message("invalid-slots", node=node)
  1388. continue
  1389. if isinstance(slots, nodes.Const):
  1390. # a string, ignore the following checks
  1391. self.add_message("single-string-used-for-slots", node=node)
  1392. continue
  1393. if not hasattr(slots, "itered"):
  1394. # we can't obtain the values, maybe a .deque?
  1395. continue
  1396. if isinstance(slots, nodes.Dict):
  1397. values = [item[0] for item in slots.items]
  1398. else:
  1399. values = slots.itered()
  1400. if isinstance(values, util.UninferableBase):
  1401. continue
  1402. for elt in values:
  1403. try:
  1404. self._check_slots_elt(elt, node)
  1405. except astroid.InferenceError:
  1406. continue
  1407. self._check_redefined_slots(node, slots, values)
  1408. def _get_classdef_slots_names(self, node: nodes.ClassDef) -> list[str]:
  1409. slots_names: list[str] = []
  1410. try:
  1411. inferred_slots = tuple(node.ilookup("__slots__"))
  1412. except astroid.InferenceError: # pragma: no cover
  1413. return slots_names
  1414. for slots in inferred_slots:
  1415. if isinstance(slots, nodes.Dict):
  1416. values = [item[0] for item in slots.items]
  1417. else:
  1418. values = slots.itered()
  1419. slots_names.extend(self._get_slots_names(values))
  1420. return slots_names
  1421. def _get_slots_names(self, slots_list: list[nodes.NodeNG]) -> list[str]:
  1422. slots_names: list[str] = []
  1423. for slot in slots_list:
  1424. if isinstance(slot, nodes.Const):
  1425. slots_names.append(slot.value)
  1426. else:
  1427. inferred_slot = safe_infer(slot)
  1428. inferred_slot_value = getattr(inferred_slot, "value", None)
  1429. if isinstance(inferred_slot_value, str):
  1430. slots_names.append(inferred_slot_value)
  1431. return slots_names
  1432. def _check_redefined_slots(
  1433. self,
  1434. node: nodes.ClassDef,
  1435. slots_node: nodes.NodeNG,
  1436. slots_list: list[nodes.NodeNG],
  1437. ) -> None:
  1438. """Check if `node` redefines a slot which is defined in an ancestor class."""
  1439. slots_names: list[str] = self._get_slots_names(slots_list)
  1440. # Slots of all parent classes
  1441. ancestors_slots_names = {
  1442. slot.value
  1443. for ancestor in node.local_attr_ancestors("__slots__")
  1444. for slot in ancestor.slots() or []
  1445. }
  1446. # Slots which are common to `node` and its parent classes
  1447. redefined_slots = ancestors_slots_names.intersection(slots_names)
  1448. if redefined_slots:
  1449. self.add_message(
  1450. "redefined-slots-in-subclass",
  1451. args=([name for name in slots_names if name in redefined_slots],),
  1452. node=slots_node,
  1453. )
  1454. def _check_slots_elt(
  1455. self, elt: SuccessfulInferenceResult, node: nodes.ClassDef
  1456. ) -> None:
  1457. for inferred in elt.infer():
  1458. match inferred:
  1459. case util.UninferableBase():
  1460. continue
  1461. case nodes.Const(value=str() as value) if value:
  1462. pass
  1463. case _:
  1464. self.add_message(
  1465. "invalid-slots-object",
  1466. args=elt.as_string(),
  1467. node=elt,
  1468. confidence=INFERENCE,
  1469. )
  1470. continue
  1471. # Check if we have a conflict with a class variable.
  1472. match class_variable := node.locals.get(inferred.value):
  1473. case [nodes.NodeNG(parent=nodes.AnnAssign(value=None))]:
  1474. # Skip annotated assignments which don't conflict at all with slots.
  1475. return
  1476. case _ if class_variable:
  1477. self.add_message(
  1478. "class-variable-slots-conflict",
  1479. args=(inferred.value,),
  1480. node=elt,
  1481. )
  1482. def leave_functiondef(self, node: nodes.FunctionDef) -> None:
  1483. """On method node, check if this method couldn't be a function.
  1484. ignore class, static and abstract methods, initializer,
  1485. methods overridden from a parent class.
  1486. """
  1487. if node.is_method():
  1488. if node.args.args is not None:
  1489. self._first_attrs.pop()
  1490. leave_asyncfunctiondef = leave_functiondef
  1491. def visit_attribute(self, node: nodes.Attribute) -> None:
  1492. """Check if the getattr is an access to a class member
  1493. if so, register it.
  1494. Also check for access to protected
  1495. class member from outside its class (but ignore __special__
  1496. methods)
  1497. """
  1498. self._check_super_without_brackets(node)
  1499. # Check self
  1500. if self._uses_mandatory_method_param(node):
  1501. self._accessed.set_accessed(node)
  1502. return
  1503. if not self.linter.is_message_enabled("protected-access"):
  1504. return
  1505. self._check_protected_attribute_access(node)
  1506. def _check_super_without_brackets(self, node: nodes.Attribute) -> None:
  1507. """Check if there is a function call on a super call without brackets."""
  1508. # Check if attribute call is in frame definition in class definition
  1509. frame = node.frame()
  1510. if not isinstance(frame, nodes.FunctionDef):
  1511. return
  1512. if not isinstance(frame.parent.frame(), nodes.ClassDef):
  1513. return
  1514. if not isinstance(node.parent, nodes.Call):
  1515. return
  1516. if not isinstance(node.expr, nodes.Name):
  1517. return
  1518. if node.expr.name == "super":
  1519. self.add_message("super-without-brackets", node=node.expr, confidence=HIGH)
  1520. @only_required_for_messages(
  1521. "assigning-non-slot", "invalid-class-object", "access-member-before-definition"
  1522. )
  1523. def visit_assignattr(self, node: nodes.AssignAttr) -> None:
  1524. if isinstance(
  1525. node.assign_type(), nodes.AugAssign
  1526. ) and self._uses_mandatory_method_param(node):
  1527. self._accessed.set_accessed(node)
  1528. self._check_in_slots(node)
  1529. self._check_invalid_class_object(node)
  1530. def _check_invalid_class_object(self, node: nodes.AssignAttr) -> None:
  1531. if not node.attrname == "__class__":
  1532. return
  1533. if isinstance(node.parent, nodes.Tuple):
  1534. class_index = -1
  1535. for i, elt in enumerate(node.parent.elts):
  1536. if hasattr(elt, "attrname") and elt.attrname == "__class__":
  1537. class_index = i
  1538. if class_index == -1:
  1539. # This should not happen because we checked that the node name
  1540. # is '__class__' earlier, but let's not be too confident here
  1541. return # pragma: no cover
  1542. inferred = safe_infer(node.parent.parent.value.elts[class_index])
  1543. else:
  1544. inferred = safe_infer(node.parent.value)
  1545. match inferred:
  1546. case nodes.ClassDef() | util.UninferableBase() | None:
  1547. # If uninferable, we allow it to prevent false positives
  1548. return
  1549. self.add_message(
  1550. "invalid-class-object",
  1551. node=node,
  1552. args=inferred.__class__.__name__,
  1553. confidence=INFERENCE,
  1554. )
  1555. def _check_in_slots(self, node: nodes.AssignAttr) -> None:
  1556. """Check that the given AssignAttr node
  1557. is defined in the class slots.
  1558. """
  1559. inferred = safe_infer(node.expr)
  1560. if not isinstance(inferred, astroid.Instance):
  1561. return
  1562. klass = inferred._proxied
  1563. if not has_known_bases(klass):
  1564. return
  1565. if "__slots__" not in klass.locals:
  1566. return
  1567. # If `__setattr__` is defined on the class, then we can't reason about
  1568. # what will happen when assigning to an attribute.
  1569. if any(
  1570. base.locals.get("__setattr__")
  1571. for base in klass.mro()
  1572. if base.qname() != "builtins.object"
  1573. ):
  1574. return
  1575. # If 'typing.Generic' is a base of bases of klass, the cached version
  1576. # of 'slots()' might have been evaluated incorrectly, thus deleted cache entry.
  1577. if any(base.qname() == "typing.Generic" for base in klass.mro()):
  1578. cache = getattr(klass, "__cache", None)
  1579. if cache and cache.get(klass.slots) is not None:
  1580. del cache[klass.slots]
  1581. slots = klass.slots()
  1582. if slots is None:
  1583. return
  1584. # If any ancestor doesn't use slots, the slots
  1585. # defined for this class are superfluous.
  1586. if any(
  1587. "__slots__" not in ancestor.locals
  1588. and ancestor.name not in ("Generic", "object")
  1589. for ancestor in klass.ancestors()
  1590. ):
  1591. return
  1592. if not any(slot.value == node.attrname for slot in slots):
  1593. # If we have a '__dict__' in slots, then
  1594. # assigning any name is valid.
  1595. if not any(slot.value == "__dict__" for slot in slots):
  1596. if _is_attribute_property(node.attrname, klass):
  1597. # Properties circumvent the slots mechanism,
  1598. # so we should not emit a warning for them.
  1599. return
  1600. if node.attrname != "__class__" and utils.is_class_attr(
  1601. node.attrname, klass
  1602. ):
  1603. return
  1604. if node.attrname in klass.locals:
  1605. for local_name in klass.locals.get(node.attrname):
  1606. statement = local_name.statement()
  1607. if (
  1608. isinstance(statement, nodes.AnnAssign)
  1609. and not statement.value
  1610. ):
  1611. return
  1612. if _has_data_descriptor(klass, node.attrname):
  1613. # Descriptors circumvent the slots mechanism as well.
  1614. return
  1615. if node.attrname == "__class__" and _has_same_layout_slots(
  1616. slots, node.parent.value
  1617. ):
  1618. return
  1619. self.add_message(
  1620. "assigning-non-slot",
  1621. args=(node.attrname,),
  1622. node=node,
  1623. confidence=INFERENCE,
  1624. )
  1625. @only_required_for_messages(
  1626. "protected-access", "no-classmethod-decorator", "no-staticmethod-decorator"
  1627. )
  1628. def visit_assign(self, assign_node: nodes.Assign) -> None:
  1629. self._check_classmethod_declaration(assign_node)
  1630. node = assign_node.targets[0]
  1631. if not isinstance(node, nodes.AssignAttr):
  1632. return
  1633. if self._uses_mandatory_method_param(node):
  1634. return
  1635. self._check_protected_attribute_access(node)
  1636. def _check_classmethod_declaration(self, node: nodes.Assign) -> None:
  1637. """Checks for uses of classmethod() or staticmethod().
  1638. When a @classmethod or @staticmethod decorator should be used instead.
  1639. A message will be emitted only if the assignment is at a class scope
  1640. and only if the classmethod's argument belongs to the class where it
  1641. is defined.
  1642. `node` is an assign node.
  1643. """
  1644. # check the function called is "classmethod" or "staticmethod"
  1645. # Check if the arg passed to classmethod is a class member
  1646. match node.value:
  1647. case nodes.Call(
  1648. func=nodes.Name(name="classmethod" | "staticmethod" as name),
  1649. args=[nodes.Name(name=method_name), *_],
  1650. ):
  1651. pass
  1652. case _:
  1653. return
  1654. msg = (
  1655. "no-classmethod-decorator"
  1656. if name == "classmethod"
  1657. else "no-staticmethod-decorator"
  1658. )
  1659. # assignment must be at a class scope
  1660. parent_class = node.scope()
  1661. if not isinstance(parent_class, nodes.ClassDef):
  1662. return
  1663. if any(method_name == member.name for member in parent_class.mymethods()):
  1664. self.add_message(msg, node=node.targets[0])
  1665. def _check_protected_attribute_access(
  1666. self, node: nodes.Attribute | nodes.AssignAttr
  1667. ) -> None:
  1668. """Given an attribute access node (set or get), check if attribute
  1669. access is legitimate.
  1670. Call _check_first_attr with node before calling
  1671. this method. Valid cases are:
  1672. * self._attr in a method or cls._attr in a classmethod. Checked by
  1673. _check_first_attr.
  1674. * Klass._attr inside "Klass" class.
  1675. * Klass2._attr inside "Klass" class when Klass2 is a base class of
  1676. Klass.
  1677. """
  1678. attrname = node.attrname
  1679. if (
  1680. not is_attr_protected(attrname)
  1681. or attrname in self.linter.config.exclude_protected
  1682. ):
  1683. return
  1684. # Typing annotations in function definitions can include protected members
  1685. if utils.is_node_in_type_annotation_context(node):
  1686. return
  1687. # Return if `attrname` is defined at the module-level or as a class attribute
  1688. # and is listed in `exclude-protected`.
  1689. inferred = safe_infer(node.expr)
  1690. if (
  1691. inferred
  1692. and isinstance(inferred, (nodes.ClassDef, nodes.Module))
  1693. and f"{inferred.name}.{attrname}" in self.linter.config.exclude_protected
  1694. ):
  1695. return
  1696. klass = node_frame_class(node)
  1697. if klass is None:
  1698. # We are not in a class, no remaining valid case
  1699. self.add_message("protected-access", node=node, args=attrname)
  1700. return
  1701. # In classes, check we are not getting a parent method
  1702. # through the class object or through super
  1703. # If the expression begins with a call to super, that's ok.
  1704. match node.expr:
  1705. case nodes.Call(func=nodes.Name(name="super")):
  1706. return
  1707. # If the expression begins with a call to type(self), that's ok.
  1708. if self._is_type_self_call(node.expr):
  1709. return
  1710. # Check if we are inside the scope of a class or nested inner class
  1711. inside_klass = True
  1712. outer_klass = klass
  1713. callee = node.expr.as_string()
  1714. parents_callee = callee.split(".")
  1715. for callee in reversed(parents_callee):
  1716. if not (outer_klass and callee == outer_klass.name):
  1717. inside_klass = False
  1718. break
  1719. # Move up one level within the nested classes
  1720. outer_klass = get_outer_class(outer_klass)
  1721. # We are in a class, one remaining valid cases, Klass._attr inside
  1722. # Klass
  1723. if not (inside_klass or callee in klass.basenames):
  1724. # Detect property assignments in the body of the class.
  1725. # This is acceptable:
  1726. #
  1727. # class A:
  1728. # b = property(lambda: self._b)
  1729. match node.parent.statement():
  1730. case nodes.Assign(
  1731. targets=[nodes.AssignName(name=name)]
  1732. ) if _is_attribute_property(name, klass):
  1733. return
  1734. if (
  1735. self._is_classmethod(node.frame())
  1736. and self._is_inferred_instance(node.expr, klass)
  1737. and self._is_class_or_instance_attribute(attrname, klass)
  1738. ):
  1739. return
  1740. licit_protected_member = not attrname.startswith("__")
  1741. if (
  1742. not self.linter.config.check_protected_access_in_special_methods
  1743. and licit_protected_member
  1744. and self._is_called_inside_special_method(node)
  1745. ):
  1746. return
  1747. self.add_message("protected-access", node=node, args=attrname)
  1748. @staticmethod
  1749. def _is_called_inside_special_method(node: nodes.NodeNG) -> bool:
  1750. """Returns true if the node is located inside a special (aka dunder) method."""
  1751. frame_name = node.frame().name
  1752. return frame_name and frame_name in PYMETHODS
  1753. def _is_type_self_call(self, expr: nodes.NodeNG) -> bool:
  1754. match expr:
  1755. case nodes.Call(func=nodes.Name(name="type"), args=[arg]):
  1756. return self._is_mandatory_method_param(arg)
  1757. return False
  1758. @staticmethod
  1759. def _is_classmethod(func: nodes.LocalsDictNodeNG) -> bool:
  1760. """Check if the given *func* node is a class method."""
  1761. return isinstance(func, nodes.FunctionDef) and (
  1762. func.type == "classmethod" or func.name == "__class_getitem__"
  1763. )
  1764. @staticmethod
  1765. def _is_inferred_instance(expr: nodes.NodeNG, klass: nodes.ClassDef) -> bool:
  1766. """Check if the inferred value of the given *expr* is an instance of
  1767. *klass*.
  1768. """
  1769. inferred = safe_infer(expr)
  1770. if not isinstance(inferred, astroid.Instance):
  1771. return False
  1772. return inferred._proxied is klass
  1773. @staticmethod
  1774. def _is_class_or_instance_attribute(name: str, klass: nodes.ClassDef) -> bool:
  1775. """Check if the given attribute *name* is a class or instance member of the
  1776. given *klass*.
  1777. Returns ``True`` if the name is a property in the given klass,
  1778. ``False`` otherwise.
  1779. """
  1780. if utils.is_class_attr(name, klass):
  1781. return True
  1782. try:
  1783. klass.instance_attr(name)
  1784. return True
  1785. except astroid.NotFoundError:
  1786. return False
  1787. def _check_accessed_members(
  1788. self, node: nodes.ClassDef, accessed: dict[str, list[_AccessNodes]]
  1789. ) -> None:
  1790. """Check that accessed members are defined."""
  1791. excs = ("AttributeError", "Exception", "BaseException")
  1792. for attr, nodes_lst in accessed.items():
  1793. try:
  1794. # is it a class attribute ?
  1795. node.local_attr(attr)
  1796. # yes, stop here
  1797. continue
  1798. except astroid.NotFoundError:
  1799. pass
  1800. # is it an instance attribute of a parent class ?
  1801. try:
  1802. next(node.instance_attr_ancestors(attr))
  1803. # yes, stop here
  1804. continue
  1805. except StopIteration:
  1806. pass
  1807. # is it an instance attribute ?
  1808. try:
  1809. defstmts = node.instance_attr(attr)
  1810. except astroid.NotFoundError:
  1811. pass
  1812. else:
  1813. # filter out augment assignment nodes
  1814. defstmts = [stmt for stmt in defstmts if stmt not in nodes_lst]
  1815. if not defstmts:
  1816. # only augment assignment for this node, no-member should be
  1817. # triggered by the typecheck checker
  1818. continue
  1819. # filter defstmts to only pick the first one when there are
  1820. # several assignments in the same scope
  1821. scope = defstmts[0].scope()
  1822. defstmts = [
  1823. stmt
  1824. for i, stmt in enumerate(defstmts)
  1825. if i == 0 or stmt.scope() is not scope
  1826. ]
  1827. # if there are still more than one, don't attempt to be smarter
  1828. # than we can be
  1829. if len(defstmts) == 1:
  1830. defstmt = defstmts[0]
  1831. # check that if the node is accessed in the same method as
  1832. # it's defined, it's accessed after the initial assignment
  1833. frame = defstmt.frame()
  1834. lno = defstmt.fromlineno
  1835. for _node in nodes_lst:
  1836. if (
  1837. _node.frame() is frame
  1838. and _node.fromlineno < lno
  1839. and not astroid.are_exclusive(
  1840. _node.statement(), defstmt, excs
  1841. )
  1842. ):
  1843. self.add_message(
  1844. "access-member-before-definition",
  1845. node=_node,
  1846. args=(attr, lno),
  1847. )
  1848. def _check_first_arg_for_type(
  1849. self, node: nodes.FunctionDef, metaclass: bool
  1850. ) -> None:
  1851. """Check the name of first argument, expect:.
  1852. * 'self' for a regular method
  1853. * 'cls' for a class method or a metaclass regular method (actually
  1854. valid-classmethod-first-arg value)
  1855. * 'mcs' for a metaclass class method (actually
  1856. valid-metaclass-classmethod-first-arg)
  1857. * not one of the above for a static method
  1858. """
  1859. # don't care about functions with unknown argument (builtins)
  1860. if node.args.args is None:
  1861. return
  1862. if node.args.posonlyargs:
  1863. first_arg = node.args.posonlyargs[0].name
  1864. elif node.args.args:
  1865. first_arg = node.argnames()[0]
  1866. else:
  1867. first_arg = None
  1868. self._first_attrs.append(first_arg)
  1869. first = self._first_attrs[-1]
  1870. # static method
  1871. if node.type == "staticmethod":
  1872. if (
  1873. first_arg == "self"
  1874. or first_arg in self.linter.config.valid_classmethod_first_arg
  1875. or first_arg in self.linter.config.valid_metaclass_classmethod_first_arg
  1876. ):
  1877. self.add_message("bad-staticmethod-argument", args=first, node=node)
  1878. return
  1879. self._first_attrs[-1] = None
  1880. elif "builtins.staticmethod" in node.decoratornames():
  1881. # Check if there is a decorator which is not named `staticmethod`
  1882. # but is assigned to one.
  1883. return
  1884. # class / regular method with no args
  1885. elif not (
  1886. node.args.args
  1887. or node.args.posonlyargs
  1888. or node.args.vararg
  1889. or node.args.kwarg
  1890. ):
  1891. self.add_message("no-method-argument", node=node, args=node.name)
  1892. # metaclass
  1893. elif metaclass:
  1894. # metaclass __new__ or classmethod
  1895. if node.type == "classmethod":
  1896. self._check_first_arg_config(
  1897. first,
  1898. self.linter.config.valid_metaclass_classmethod_first_arg,
  1899. node,
  1900. "bad-mcs-classmethod-argument",
  1901. node.name,
  1902. )
  1903. # metaclass regular method
  1904. else:
  1905. self._check_first_arg_config(
  1906. first,
  1907. self.linter.config.valid_classmethod_first_arg,
  1908. node,
  1909. "bad-mcs-method-argument",
  1910. node.name,
  1911. )
  1912. # regular class with class method
  1913. elif node.type == "classmethod" or node.name == "__class_getitem__":
  1914. self._check_first_arg_config(
  1915. first,
  1916. self.linter.config.valid_classmethod_first_arg,
  1917. node,
  1918. "bad-classmethod-argument",
  1919. node.name,
  1920. )
  1921. # regular class with regular method without self as argument
  1922. elif first != "self":
  1923. self.add_message("no-self-argument", node=node, args=node.name)
  1924. def _check_first_arg_config(
  1925. self,
  1926. first: str | None,
  1927. config: Sequence[str],
  1928. node: nodes.FunctionDef,
  1929. message: str,
  1930. method_name: str,
  1931. ) -> None:
  1932. if first not in config:
  1933. if len(config) == 1:
  1934. valid = repr(config[0])
  1935. else:
  1936. valid = ", ".join(repr(v) for v in config[:-1])
  1937. valid = f"{valid} or {config[-1]!r}"
  1938. self.add_message(message, args=(method_name, valid), node=node)
  1939. def _check_bases_classes(self, node: nodes.ClassDef) -> None:
  1940. """Check that the given class node implements abstract methods from
  1941. base classes.
  1942. """
  1943. def is_abstract(method: nodes.FunctionDef) -> bool:
  1944. return method.is_abstract(pass_is_abstract=False) # type: ignore[no-any-return]
  1945. # check if this class abstract
  1946. if class_is_abstract(node):
  1947. return
  1948. methods = sorted(
  1949. unimplemented_abstract_methods(node, is_abstract).items(),
  1950. key=lambda item: item[0],
  1951. )
  1952. for name, method in methods:
  1953. owner = method.parent.frame()
  1954. if owner is node:
  1955. continue
  1956. # owner is not this class, it must be a parent class
  1957. # check that the ancestor's method is not abstract
  1958. if name in node.locals:
  1959. # it is redefined as an attribute or with a descriptor
  1960. continue
  1961. self.add_message(
  1962. "abstract-method",
  1963. node=node,
  1964. args=(name, owner.name, node.name),
  1965. confidence=INFERENCE,
  1966. )
  1967. def _check_init(self, node: nodes.FunctionDef, klass_node: nodes.ClassDef) -> None:
  1968. """Check that the __init__ method call super or ancestors'__init__
  1969. method (unless it is used for type hinting with `typing.overload`).
  1970. """
  1971. if not self.linter.is_message_enabled(
  1972. "super-init-not-called"
  1973. ) and not self.linter.is_message_enabled("non-parent-init-called"):
  1974. return
  1975. to_call = _ancestors_to_call(klass_node)
  1976. not_called_yet = dict(to_call)
  1977. parents_with_called_inits: set[bases.UnboundMethod] = set()
  1978. for stmt in node.nodes_of_class(nodes.Call):
  1979. expr = stmt.func
  1980. if not (isinstance(expr, nodes.Attribute) and expr.attrname == "__init__"):
  1981. continue
  1982. # skip the test if using super
  1983. match expr.expr:
  1984. case nodes.Call(func=nodes.Name(name="super")):
  1985. return
  1986. try:
  1987. for klass in expr.expr.infer():
  1988. if isinstance(klass, util.UninferableBase):
  1989. continue
  1990. # The inferred klass can be super(), which was
  1991. # assigned to a variable and the `__init__`
  1992. # was called later.
  1993. #
  1994. # base = super()
  1995. # base.__init__(...)
  1996. match klass:
  1997. case astroid.Instance(
  1998. _proxied=nodes.ClassDef(name="super") as p
  1999. ) if is_builtin_object(p):
  2000. return
  2001. case objects.Super():
  2002. return
  2003. try:
  2004. method = not_called_yet.pop(klass)
  2005. # Record that the class' init has been called
  2006. parents_with_called_inits.add(node_frame_class(method))
  2007. except KeyError:
  2008. if klass not in klass_node.ancestors(recurs=False):
  2009. self.add_message(
  2010. "non-parent-init-called", node=expr, args=klass.name
  2011. )
  2012. except astroid.InferenceError:
  2013. continue
  2014. for klass, method in not_called_yet.items():
  2015. # Check if the init of the class that defines this init has already
  2016. # been called.
  2017. if node_frame_class(method) in parents_with_called_inits:
  2018. return
  2019. if utils.is_protocol_class(klass):
  2020. return
  2021. if decorated_with(node, ["typing.overload"]):
  2022. continue
  2023. self.add_message(
  2024. "super-init-not-called",
  2025. args=klass.name,
  2026. node=node,
  2027. confidence=INFERENCE,
  2028. )
  2029. def _check_signature(
  2030. self,
  2031. method1: nodes.FunctionDef,
  2032. refmethod: nodes.FunctionDef,
  2033. cls: nodes.ClassDef,
  2034. ) -> None:
  2035. """Check that the signature of the two given methods match."""
  2036. if not (
  2037. isinstance(method1, nodes.FunctionDef)
  2038. and isinstance(refmethod, nodes.FunctionDef)
  2039. ):
  2040. self.add_message(
  2041. "method-check-failed", args=(method1, refmethod), node=method1
  2042. )
  2043. return
  2044. instance = cls.instantiate_class()
  2045. method1 = astroid.scoped_nodes.function_to_method(method1, instance)
  2046. refmethod = astroid.scoped_nodes.function_to_method(refmethod, instance)
  2047. # Don't care about functions with unknown argument (builtins).
  2048. if method1.args.args is None or refmethod.args.args is None:
  2049. return
  2050. # Ignore private to class methods.
  2051. if is_attr_private(method1.name):
  2052. return
  2053. # Ignore setters, they have an implicit extra argument,
  2054. # which shouldn't be taken in consideration.
  2055. if is_property_setter(method1):
  2056. return
  2057. arg_differ_output = _different_parameters(
  2058. refmethod, method1, dummy_parameter_regex=self._dummy_rgx
  2059. )
  2060. class_type = "overriding"
  2061. if len(arg_differ_output) > 0:
  2062. for msg in arg_differ_output:
  2063. if "Number" in msg:
  2064. total_args_method1 = len(method1.args.args)
  2065. if method1.args.vararg:
  2066. total_args_method1 += 1
  2067. if method1.args.kwarg:
  2068. total_args_method1 += 1
  2069. if method1.args.kwonlyargs:
  2070. total_args_method1 += len(method1.args.kwonlyargs)
  2071. total_args_refmethod = len(refmethod.args.args)
  2072. if refmethod.args.vararg:
  2073. total_args_refmethod += 1
  2074. if refmethod.args.kwarg:
  2075. total_args_refmethod += 1
  2076. if refmethod.args.kwonlyargs:
  2077. total_args_refmethod += len(refmethod.args.kwonlyargs)
  2078. error_type = "arguments-differ"
  2079. msg_args = (
  2080. msg
  2081. + f"was {total_args_refmethod} in '{refmethod.parent.frame().name}.{refmethod.name}' and "
  2082. f"is now {total_args_method1} in",
  2083. class_type,
  2084. f"{method1.parent.frame().name}.{method1.name}",
  2085. )
  2086. elif "renamed" in msg:
  2087. error_type = "arguments-renamed"
  2088. msg_args = (
  2089. msg,
  2090. class_type,
  2091. f"{method1.parent.frame().name}.{method1.name}",
  2092. )
  2093. else:
  2094. error_type = "arguments-differ"
  2095. msg_args = (
  2096. msg,
  2097. class_type,
  2098. f"{method1.parent.frame().name}.{method1.name}",
  2099. )
  2100. self.add_message(error_type, args=msg_args, node=method1)
  2101. elif (
  2102. len(method1.args.defaults) < len(refmethod.args.defaults)
  2103. and not method1.args.vararg
  2104. ):
  2105. class_type = "overridden"
  2106. self.add_message(
  2107. "signature-differs", args=(class_type, method1.name), node=method1
  2108. )
  2109. def _uses_mandatory_method_param(
  2110. self, node: nodes.Attribute | nodes.Assign | nodes.AssignAttr
  2111. ) -> bool:
  2112. """Check that attribute lookup name use first attribute variable name.
  2113. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
  2114. """
  2115. return self._is_mandatory_method_param(node.expr)
  2116. def _is_mandatory_method_param(self, node: nodes.NodeNG) -> bool:
  2117. """Check if nodes.Name corresponds to first attribute variable name.
  2118. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
  2119. Static methods return False.
  2120. """
  2121. if self._first_attrs:
  2122. first_attr = self._first_attrs[-1]
  2123. else:
  2124. # It's possible the function was already unregistered.
  2125. match closest_func := utils.get_node_first_ancestor_of_type(
  2126. node, nodes.FunctionDef
  2127. ):
  2128. case nodes.FunctionDef(
  2129. args=nodes.Arguments(args=[nodes.AssignName(name=first_attr), *_])
  2130. ) if closest_func.is_bound():
  2131. pass
  2132. case _:
  2133. return False
  2134. # pylint: disable=possibly-used-before-assignment
  2135. return isinstance(node, nodes.Name) and node.name == first_attr
  2136. def _ancestors_to_call(
  2137. klass_node: nodes.ClassDef, method_name: str = "__init__"
  2138. ) -> dict[nodes.ClassDef, bases.UnboundMethod]:
  2139. """Return a dictionary where keys are the list of base classes providing
  2140. the queried method, and so that should/may be called from the method node.
  2141. """
  2142. to_call: dict[nodes.ClassDef, bases.UnboundMethod] = {}
  2143. for base_node in klass_node.ancestors(recurs=False):
  2144. try:
  2145. init_node = next(base_node.igetattr(method_name))
  2146. if not isinstance(init_node, astroid.UnboundMethod):
  2147. continue
  2148. if init_node.is_abstract():
  2149. continue
  2150. to_call[base_node] = init_node
  2151. except astroid.InferenceError:
  2152. continue
  2153. return to_call