Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

classes.py 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2010 Maarten ter Huurne <maarten@treewalker.org>
  4. # Copyright (c) 2012-2014 Google, Inc.
  5. # Copyright (c) 2012 FELD Boris <lothiraldan@gmail.com>
  6. # Copyright (c) 2013-2017 Claudiu Popa <pcmanticore@gmail.com>
  7. # Copyright (c) 2014 Michal Nowikowski <godfryd@gmail.com>
  8. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  9. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  10. # Copyright (c) 2014 David Pursehouse <david.pursehouse@gmail.com>
  11. # Copyright (c) 2015 Dmitry Pribysh <dmand@yandex.ru>
  12. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  13. # Copyright (c) 2016-2017 Łukasz Rogalski <rogalski.91@gmail.com>
  14. # Copyright (c) 2016 Alexander Todorov <atodorov@otb.bg>
  15. # Copyright (c) 2016 Anthony Foglia <afoglia@users.noreply.github.com>
  16. # Copyright (c) 2016 Florian Bruhin <me@the-compiler.org>
  17. # Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
  18. # Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net>
  19. # Copyright (c) 2017 hippo91 <guillaume.peillex@gmail.com>
  20. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  22. """classes checker for Python code
  23. """
  24. from __future__ import generators
  25. import collections
  26. import sys
  27. import six
  28. import astroid
  29. from astroid.bases import Generator, BUILTINS
  30. from astroid.exceptions import InconsistentMroError, DuplicateBasesError
  31. from astroid import decorators
  32. from astroid import objects
  33. from astroid.scoped_nodes import function_to_method
  34. from pylint.interfaces import IAstroidChecker
  35. from pylint.checkers import BaseChecker
  36. from pylint.checkers.utils import (
  37. PYMETHODS, SPECIAL_METHODS_PARAMS,
  38. overrides_a_method, check_messages, is_attr_private,
  39. is_attr_protected, node_frame_class, is_builtin_object,
  40. decorated_with_property, unimplemented_abstract_methods,
  41. decorated_with, class_is_abstract,
  42. safe_infer, has_known_bases, is_iterable, is_comprehension)
  43. from pylint.utils import get_global_option
  44. if sys.version_info >= (3, 0):
  45. NEXT_METHOD = '__next__'
  46. else:
  47. NEXT_METHOD = 'next'
  48. INVALID_BASE_CLASSES = {'bool', 'range', 'slice', 'memoryview'}
  49. # Dealing with useless override detection, with regard
  50. # to parameters vs arguments
  51. _CallSignature = collections.namedtuple(
  52. '_CallSignature', 'args kws starred_args starred_kws')
  53. _ParameterSignature = collections.namedtuple(
  54. '_ParameterSignature',
  55. 'args kwonlyargs varargs kwargs',
  56. )
  57. def _signature_from_call(call):
  58. kws = {}
  59. args = []
  60. starred_kws = []
  61. starred_args = []
  62. for keyword in call.keywords or []:
  63. arg, value = keyword.arg, keyword.value
  64. if arg is None and isinstance(value, astroid.Name):
  65. # Starred node and we are interested only in names,
  66. # otherwise some transformation might occur for the parameter.
  67. starred_kws.append(value.name)
  68. elif isinstance(value, astroid.Name):
  69. kws[arg] = value.name
  70. else:
  71. kws[arg] = None
  72. for arg in call.args:
  73. if isinstance(arg, astroid.Starred) and isinstance(arg.value, astroid.Name):
  74. # Positional variadic and a name, otherwise some transformation
  75. # might have occurred.
  76. starred_args.append(arg.value.name)
  77. elif isinstance(arg, astroid.Name):
  78. args.append(arg.name)
  79. else:
  80. args.append(None)
  81. return _CallSignature(args, kws, starred_args, starred_kws)
  82. def _signature_from_arguments(arguments):
  83. kwarg = arguments.kwarg
  84. vararg = arguments.vararg
  85. args = [arg.name for arg in arguments.args if arg.name != 'self']
  86. kwonlyargs = [arg.name for arg in arguments.kwonlyargs]
  87. return _ParameterSignature(args, kwonlyargs, vararg, kwarg)
  88. def _definition_equivalent_to_call(definition, call):
  89. '''Check if a definition signature is equivalent to a call.'''
  90. if definition.kwargs:
  91. same_kw_variadics = definition.kwargs in call.starred_kws
  92. else:
  93. same_kw_variadics = not call.starred_kws
  94. if definition.varargs:
  95. same_args_variadics = definition.varargs in call.starred_args
  96. else:
  97. same_args_variadics = not call.starred_args
  98. same_kwonlyargs = all(kw in call.kws for kw in definition.kwonlyargs)
  99. same_args = definition.args == call.args
  100. no_additional_kwarg_arguments = True
  101. if call.kws:
  102. for keyword in call.kws:
  103. is_arg = keyword in call.args
  104. is_kwonly = keyword in definition.kwonlyargs
  105. if not is_arg and not is_kwonly:
  106. # Maybe this argument goes into **kwargs,
  107. # or it is an extraneous argument.
  108. # In any case, the signature is different than
  109. # the call site, which stops our search.
  110. no_additional_kwarg_arguments = False
  111. break
  112. return all((
  113. same_args,
  114. same_kwonlyargs,
  115. same_args_variadics,
  116. same_kw_variadics,
  117. no_additional_kwarg_arguments,
  118. ))
  119. # Deal with parameters overridding in two methods.
  120. def _positional_parameters(method):
  121. positional = method.args.args
  122. if method.type in ('classmethod', 'method'):
  123. positional = positional[1:]
  124. return positional
  125. def _get_node_type(node, potential_types):
  126. """
  127. Return the type of the node if it exists in potential_types.
  128. Args:
  129. node (astroid.node): node to get the type of.
  130. potential_types (tuple): potential types of the node.
  131. Returns:
  132. type: type of the node or None.
  133. """
  134. for potential_type in potential_types:
  135. if isinstance(node, potential_type):
  136. return potential_type
  137. return None
  138. def _check_arg_equality(node_a, node_b, attr_name):
  139. """
  140. Check equality of nodes based on the comparison of their attributes named attr_name.
  141. Args:
  142. node_a (astroid.node): first node to compare.
  143. node_b (astroid.node): second node to compare.
  144. attr_name (str): name of the nodes attribute to use for comparison.
  145. Returns:
  146. bool: True if node_a.attr_name == node_b.attr_name, False otherwise.
  147. """
  148. return getattr(node_a, attr_name) == getattr(node_b, attr_name)
  149. def _has_different_parameters_default_value(original, overridden):
  150. """
  151. Check if original and overridden methods arguments have different default values
  152. Return True if one of the overridden arguments has a default
  153. value different from the default value of the original argument
  154. If one of the method doesn't have argument (.args is None)
  155. return False
  156. """
  157. if original.args is None or overridden.args is None:
  158. return False
  159. original_param_names = [param.name for param in original.args]
  160. default_missing = object()
  161. for param_name in original_param_names:
  162. try:
  163. original_default = original.default_value(param_name)
  164. except astroid.exceptions.NoDefault:
  165. original_default = default_missing
  166. try:
  167. overridden_default = overridden.default_value(param_name)
  168. except astroid.exceptions.NoDefault:
  169. overridden_default = default_missing
  170. default_list = [arg == default_missing for arg in (original_default, overridden_default)]
  171. if any(default_list) and not all(default_list):
  172. # Only one arg has no default value
  173. return True
  174. astroid_type_compared_attr = {astroid.Const: "value", astroid.ClassDef: "name",
  175. astroid.Tuple: "elts", astroid.List: "elts"}
  176. handled_types = tuple(astroid_type for astroid_type in astroid_type_compared_attr)
  177. original_type = _get_node_type(original_default, handled_types)
  178. if original_type:
  179. # We handle only astroid types that are inside the dict astroid_type_compared_attr
  180. if not isinstance(overridden_default, original_type):
  181. # Two args with same name but different types
  182. return True
  183. if not _check_arg_equality(original_default, overridden_default,
  184. astroid_type_compared_attr[original_type]):
  185. # Two args with same type but different values
  186. return True
  187. return False
  188. def _has_different_parameters(original, overridden, dummy_parameter_regex):
  189. zipped = six.moves.zip_longest(original, overridden)
  190. for original_param, overridden_param in zipped:
  191. params = (original_param, overridden_param)
  192. if not all(params):
  193. return True
  194. names = [param.name for param in params]
  195. if any(map(dummy_parameter_regex.match, names)):
  196. continue
  197. if original_param.name != overridden_param.name:
  198. return True
  199. return False
  200. def _different_parameters(original, overridden, dummy_parameter_regex):
  201. """Determine if the two methods have different parameters
  202. They are considered to have different parameters if:
  203. * they have different positional parameters, including different names
  204. * one of the methods is having variadics, while the other is not
  205. * they have different keyword only parameters.
  206. """
  207. original_parameters = _positional_parameters(original)
  208. overridden_parameters = _positional_parameters(overridden)
  209. different_positional = _has_different_parameters(
  210. original_parameters,
  211. overridden_parameters,
  212. dummy_parameter_regex)
  213. different_kwonly = _has_different_parameters(
  214. original.args.kwonlyargs,
  215. overridden.args.kwonlyargs,
  216. dummy_parameter_regex)
  217. if original.name in PYMETHODS:
  218. # Ignore the difference for special methods. If the parameter
  219. # numbers are different, then that is going to be caught by
  220. # unexpected-special-method-signature.
  221. # If the names are different, it doesn't matter, since they can't
  222. # be used as keyword arguments anyway.
  223. different_positional = different_kwonly = False
  224. # Both or none should have extra variadics, otherwise the method
  225. # loses or gains capabilities that are not reflected into the parent method,
  226. # leading to potential inconsistencies in the code.
  227. different_kwarg = sum(
  228. 1 for param in (original.args.kwarg, overridden.args.kwarg)
  229. if not param) == 1
  230. different_vararg = sum(
  231. 1 for param in (original.args.vararg, overridden.args.vararg)
  232. if not param) == 1
  233. return any((
  234. different_positional,
  235. different_kwarg,
  236. different_vararg,
  237. different_kwonly
  238. ))
  239. def _is_invalid_base_class(cls):
  240. return cls.name in INVALID_BASE_CLASSES and is_builtin_object(cls)
  241. def _has_data_descriptor(cls, attr):
  242. attributes = cls.getattr(attr)
  243. for attribute in attributes:
  244. try:
  245. for inferred in attribute.infer():
  246. if isinstance(inferred, astroid.Instance):
  247. try:
  248. inferred.getattr('__get__')
  249. inferred.getattr('__set__')
  250. except astroid.NotFoundError:
  251. continue
  252. else:
  253. return True
  254. except astroid.InferenceError:
  255. # Can't infer, avoid emitting a false positive in this case.
  256. return True
  257. return False
  258. def _called_in_methods(func, klass, methods):
  259. """ Check if the func was called in any of the given methods,
  260. belonging to the *klass*. Returns True if so, False otherwise.
  261. """
  262. if not isinstance(func, astroid.FunctionDef):
  263. return False
  264. for method in methods:
  265. try:
  266. infered = klass.getattr(method)
  267. except astroid.NotFoundError:
  268. continue
  269. for infer_method in infered:
  270. for call in infer_method.nodes_of_class(astroid.Call):
  271. try:
  272. bound = next(call.func.infer())
  273. except (astroid.InferenceError, StopIteration):
  274. continue
  275. if not isinstance(bound, astroid.BoundMethod):
  276. continue
  277. func_obj = bound._proxied
  278. if isinstance(func_obj, astroid.UnboundMethod):
  279. func_obj = func_obj._proxied
  280. if func_obj.name == func.name:
  281. return True
  282. return False
  283. def _is_attribute_property(name, klass):
  284. """ Check if the given attribute *name* is a property
  285. in the given *klass*.
  286. It will look for `property` calls or for functions
  287. with the given name, decorated by `property` or `property`
  288. subclasses.
  289. Returns ``True`` if the name is a property in the given klass,
  290. ``False`` otherwise.
  291. """
  292. try:
  293. attributes = klass.getattr(name)
  294. except astroid.NotFoundError:
  295. return False
  296. property_name = "{0}.property".format(BUILTINS)
  297. for attr in attributes:
  298. try:
  299. infered = next(attr.infer())
  300. except astroid.InferenceError:
  301. continue
  302. if (isinstance(infered, astroid.FunctionDef) and
  303. decorated_with_property(infered)):
  304. return True
  305. if infered.pytype() == property_name:
  306. return True
  307. return False
  308. def _has_bare_super_call(fundef_node):
  309. for call in fundef_node.nodes_of_class(astroid.Call):
  310. func = call.func
  311. if (isinstance(func, astroid.Name) and
  312. func.name == 'super' and
  313. not call.args):
  314. return True
  315. return False
  316. def _safe_infer_call_result(node, caller, context=None):
  317. """
  318. Safely infer the return value of a function.
  319. Returns None if inference failed or if there is some ambiguity (more than
  320. one node has been inferred). Otherwise returns infered value.
  321. """
  322. try:
  323. inferit = node.infer_call_result(caller, context=context)
  324. value = next(inferit)
  325. except astroid.InferenceError:
  326. return None # inference failed
  327. except StopIteration:
  328. return None # no values infered
  329. try:
  330. next(inferit)
  331. return None # there is ambiguity on the inferred node
  332. except astroid.InferenceError:
  333. return None # there is some kind of ambiguity
  334. except StopIteration:
  335. return value
  336. def _has_same_layout_slots(slots, assigned_value):
  337. inferred = next(assigned_value.infer())
  338. if isinstance(inferred, astroid.ClassDef):
  339. other_slots = inferred.slots()
  340. if all(first_slot and second_slot and first_slot.value == second_slot.value
  341. for (first_slot, second_slot) in six.moves.zip_longest(slots, other_slots)):
  342. return True
  343. return False
  344. MSGS = {
  345. 'F0202': ('Unable to check methods signature (%s / %s)',
  346. 'method-check-failed',
  347. 'Used when Pylint has been unable to check methods signature '
  348. 'compatibility for an unexpected reason. Please report this kind '
  349. 'if you don\'t make sense of it.'),
  350. 'E0202': ('An attribute defined in %s line %s hides this method',
  351. 'method-hidden',
  352. 'Used when a class defines a method which is hidden by an '
  353. 'instance attribute from an ancestor class or set by some '
  354. 'client code.'),
  355. 'E0203': ('Access to member %r before its definition line %s',
  356. 'access-member-before-definition',
  357. 'Used when an instance member is accessed before it\'s actually '
  358. 'assigned.'),
  359. 'W0201': ('Attribute %r defined outside __init__',
  360. 'attribute-defined-outside-init',
  361. 'Used when an instance attribute is defined outside the __init__ '
  362. 'method.'),
  363. 'W0212': ('Access to a protected member %s of a client class', # E0214
  364. 'protected-access',
  365. 'Used when a protected member (i.e. class member with a name '
  366. 'beginning with an underscore) is access outside the class or a '
  367. 'descendant of the class where it\'s defined.'),
  368. 'E0211': ('Method has no argument',
  369. 'no-method-argument',
  370. 'Used when a method which should have the bound instance as '
  371. 'first argument has no argument defined.'),
  372. 'E0213': ('Method should have "self" as first argument',
  373. 'no-self-argument',
  374. 'Used when a method has an attribute different the "self" as '
  375. 'first argument. This is considered as an error since this is '
  376. 'a so common convention that you shouldn\'t break it!'),
  377. 'C0202': ('Class method %s should have %s as first argument',
  378. 'bad-classmethod-argument',
  379. 'Used when a class method has a first argument named differently '
  380. 'than the value specified in valid-classmethod-first-arg option '
  381. '(default to "cls"), recommended to easily differentiate them '
  382. 'from regular instance methods.'),
  383. 'C0203': ('Metaclass method %s should have %s as first argument',
  384. 'bad-mcs-method-argument',
  385. 'Used when a metaclass method has a first argument named '
  386. 'differently than the value specified in valid-classmethod-first'
  387. '-arg option (default to "cls"), recommended to easily '
  388. 'differentiate them from regular instance methods.'),
  389. 'C0204': ('Metaclass class method %s should have %s as first argument',
  390. 'bad-mcs-classmethod-argument',
  391. 'Used when a metaclass class method has a first argument named '
  392. 'differently than the value specified in valid-metaclass-'
  393. 'classmethod-first-arg option (default to "mcs"), recommended to '
  394. 'easily differentiate them from regular instance methods.'),
  395. 'W0211': ('Static method with %r as first argument',
  396. 'bad-staticmethod-argument',
  397. 'Used when a static method has "self" or a value specified in '
  398. 'valid-classmethod-first-arg option or '
  399. 'valid-metaclass-classmethod-first-arg option as first argument.'
  400. ),
  401. 'R0201': ('Method could be a function',
  402. 'no-self-use',
  403. 'Used when a method doesn\'t use its bound instance, and so could '
  404. 'be written as a function.'
  405. ),
  406. 'W0221': ('Parameters differ from %s %r method',
  407. 'arguments-differ',
  408. 'Used when a method has a different number of arguments than in '
  409. 'the implemented interface or in an overridden method.'),
  410. 'W0222': ('Signature differs from %s %r method',
  411. 'signature-differs',
  412. 'Used when a method signature is different than in the '
  413. 'implemented interface or in an overridden method.'),
  414. 'W0223': ('Method %r is abstract in class %r but is not overridden',
  415. 'abstract-method',
  416. 'Used when an abstract method (i.e. raise NotImplementedError) is '
  417. 'not overridden in concrete class.'
  418. ),
  419. 'W0231': ('__init__ method from base class %r is not called',
  420. 'super-init-not-called',
  421. 'Used when an ancestor class method has an __init__ method '
  422. 'which is not called by a derived class.'),
  423. 'W0232': ('Class has no __init__ method',
  424. 'no-init',
  425. 'Used when a class has no __init__ method, neither its parent '
  426. 'classes.'),
  427. 'W0233': ('__init__ method from a non direct base class %r is called',
  428. 'non-parent-init-called',
  429. 'Used when an __init__ method is called on a class which is not '
  430. 'in the direct ancestors for the analysed class.'),
  431. 'W0235': ('Useless super delegation in method %r',
  432. 'useless-super-delegation',
  433. 'Used whenever we can detect that an overridden method is useless, '
  434. 'relying on super() delegation to do the same thing as another method '
  435. 'from the MRO.'),
  436. 'E0236': ('Invalid object %r in __slots__, must contain '
  437. 'only non empty strings',
  438. 'invalid-slots-object',
  439. 'Used when an invalid (non-string) object occurs in __slots__.'),
  440. 'E0237': ('Assigning to attribute %r not defined in class slots',
  441. 'assigning-non-slot',
  442. 'Used when assigning to an attribute not defined '
  443. 'in the class slots.'),
  444. 'E0238': ('Invalid __slots__ object',
  445. 'invalid-slots',
  446. 'Used when an invalid __slots__ is found in class. '
  447. 'Only a string, an iterable or a sequence is permitted.'),
  448. 'E0239': ('Inheriting %r, which is not a class.',
  449. 'inherit-non-class',
  450. 'Used when a class inherits from something which is not a '
  451. 'class.'),
  452. 'E0240': ('Inconsistent method resolution order for class %r',
  453. 'inconsistent-mro',
  454. 'Used when a class has an inconsistent method resolution order.'),
  455. 'E0241': ('Duplicate bases for class %r',
  456. 'duplicate-bases',
  457. 'Used when a class has duplicate bases.'),
  458. 'R0202': ('Consider using a decorator instead of calling classmethod',
  459. 'no-classmethod-decorator',
  460. 'Used when a class method is defined without using the decorator '
  461. 'syntax.'),
  462. 'R0203': ('Consider using a decorator instead of calling staticmethod',
  463. 'no-staticmethod-decorator',
  464. 'Used when a static method is defined without using the decorator '
  465. 'syntax.'),
  466. 'C0205': ('Class __slots__ should be a non-string iterable',
  467. 'single-string-used-for-slots',
  468. 'Used when a class __slots__ is a simple string, rather '
  469. 'than an iterable.'),
  470. }
  471. class ScopeAccessMap(object):
  472. """Store the accessed variables per scope."""
  473. def __init__(self):
  474. self._scopes = collections.defaultdict(
  475. lambda: collections.defaultdict(list)
  476. )
  477. def set_accessed(self, node):
  478. """Set the given node as accessed."""
  479. frame = node_frame_class(node)
  480. if frame is None:
  481. # The node does not live in a class.
  482. return
  483. self._scopes[frame][node.attrname].append(node)
  484. def accessed(self, scope):
  485. """Get the accessed variables for the given scope."""
  486. return self._scopes.get(scope, {})
  487. class ClassChecker(BaseChecker):
  488. """checks for :
  489. * methods without self as first argument
  490. * overridden methods signature
  491. * access only to existent members via self
  492. * attributes not defined in the __init__ method
  493. * unreachable code
  494. """
  495. __implements__ = (IAstroidChecker,)
  496. # configuration section name
  497. name = 'classes'
  498. # messages
  499. msgs = MSGS
  500. priority = -2
  501. # configuration options
  502. options = (('defining-attr-methods',
  503. {'default' : ('__init__', '__new__', 'setUp'),
  504. 'type' : 'csv',
  505. 'metavar' : '<method names>',
  506. 'help' : 'List of method names used to declare (i.e. assign) \
  507. instance attributes.'}
  508. ),
  509. ('valid-classmethod-first-arg',
  510. {'default' : ('cls',),
  511. 'type' : 'csv',
  512. 'metavar' : '<argument names>',
  513. 'help' : 'List of valid names for the first argument in \
  514. a class method.'}
  515. ),
  516. ('valid-metaclass-classmethod-first-arg',
  517. {'default' : ('mcs',),
  518. 'type' : 'csv',
  519. 'metavar' : '<argument names>',
  520. 'help' : 'List of valid names for the first argument in \
  521. a metaclass class method.'}
  522. ),
  523. ('exclude-protected',
  524. {
  525. 'default': (
  526. # namedtuple public API.
  527. '_asdict', '_fields', '_replace', '_source', '_make'),
  528. 'type': 'csv',
  529. 'metavar': '<protected access exclusions>',
  530. 'help': ('List of member names, which should be excluded '
  531. 'from the protected access warning.')}
  532. ))
  533. def __init__(self, linter=None):
  534. BaseChecker.__init__(self, linter)
  535. self._accessed = ScopeAccessMap()
  536. self._first_attrs = []
  537. self._meth_could_be_func = None
  538. @decorators.cachedproperty
  539. def _dummy_rgx(self):
  540. return get_global_option(
  541. self, 'dummy-variables-rgx', default=None)
  542. @decorators.cachedproperty
  543. def _ignore_mixin(self):
  544. return get_global_option(
  545. self, 'ignore-mixin-members', default=True)
  546. def visit_classdef(self, node):
  547. """init visit variable _accessed
  548. """
  549. self._check_bases_classes(node)
  550. # if not an exception or a metaclass
  551. if node.type == 'class' and has_known_bases(node):
  552. try:
  553. node.local_attr('__init__')
  554. except astroid.NotFoundError:
  555. self.add_message('no-init', args=node, node=node)
  556. self._check_slots(node)
  557. self._check_proper_bases(node)
  558. self._check_consistent_mro(node)
  559. def _check_consistent_mro(self, node):
  560. """Detect that a class has a consistent mro or duplicate bases."""
  561. try:
  562. node.mro()
  563. except InconsistentMroError:
  564. self.add_message('inconsistent-mro', args=node.name, node=node)
  565. except DuplicateBasesError:
  566. self.add_message('duplicate-bases', args=node.name, node=node)
  567. except NotImplementedError:
  568. # Old style class, there's no mro so don't do anything.
  569. pass
  570. def _check_proper_bases(self, node):
  571. """
  572. Detect that a class inherits something which is not
  573. a class or a type.
  574. """
  575. for base in node.bases:
  576. ancestor = safe_infer(base)
  577. if ancestor in (astroid.YES, None):
  578. continue
  579. if (isinstance(ancestor, astroid.Instance) and
  580. ancestor.is_subtype_of('%s.type' % (BUILTINS,))):
  581. continue
  582. if (not isinstance(ancestor, astroid.ClassDef) or
  583. _is_invalid_base_class(ancestor)):
  584. self.add_message('inherit-non-class',
  585. args=base.as_string(), node=node)
  586. def leave_classdef(self, cnode):
  587. """close a class node:
  588. check that instance attributes are defined in __init__ and check
  589. access to existent members
  590. """
  591. # check access to existent members on non metaclass classes
  592. if self._ignore_mixin and cnode.name[-5:].lower() == 'mixin':
  593. # We are in a mixin class. No need to try to figure out if
  594. # something is missing, since it is most likely that it will
  595. # miss.
  596. return
  597. accessed = self._accessed.accessed(cnode)
  598. if cnode.type != 'metaclass':
  599. self._check_accessed_members(cnode, accessed)
  600. # checks attributes are defined in an allowed method such as __init__
  601. if not self.linter.is_message_enabled('attribute-defined-outside-init'):
  602. return
  603. defining_methods = self.config.defining_attr_methods
  604. current_module = cnode.root()
  605. for attr, nodes in six.iteritems(cnode.instance_attrs):
  606. # skip nodes which are not in the current module and it may screw up
  607. # the output, while it's not worth it
  608. nodes = [n for n in nodes if not
  609. isinstance(n.statement(), (astroid.Delete, astroid.AugAssign))
  610. and n.root() is current_module]
  611. if not nodes:
  612. continue # error detected by typechecking
  613. # check if any method attr is defined in is a defining method
  614. if any(node.frame().name in defining_methods
  615. for node in nodes):
  616. continue
  617. # check attribute is defined in a parent's __init__
  618. for parent in cnode.instance_attr_ancestors(attr):
  619. attr_defined = False
  620. # check if any parent method attr is defined in is a defining method
  621. for node in parent.instance_attrs[attr]:
  622. if node.frame().name in defining_methods:
  623. attr_defined = True
  624. if attr_defined:
  625. # we're done :)
  626. break
  627. else:
  628. # check attribute is defined as a class attribute
  629. try:
  630. cnode.local_attr(attr)
  631. except astroid.NotFoundError:
  632. for node in nodes:
  633. if node.frame().name not in defining_methods:
  634. # If the attribute was set by a call in any
  635. # of the defining methods, then don't emit
  636. # the warning.
  637. if _called_in_methods(node.frame(), cnode,
  638. defining_methods):
  639. continue
  640. self.add_message('attribute-defined-outside-init',
  641. args=attr, node=node)
  642. def visit_functiondef(self, node):
  643. """check method arguments, overriding"""
  644. # ignore actual functions
  645. if not node.is_method():
  646. return
  647. self._check_useless_super_delegation(node)
  648. klass = node.parent.frame()
  649. self._meth_could_be_func = True
  650. # check first argument is self if this is actually a method
  651. self._check_first_arg_for_type(node, klass.type == 'metaclass')
  652. if node.name == '__init__':
  653. self._check_init(node)
  654. return
  655. # check signature if the method overloads inherited method
  656. for overridden in klass.local_attr_ancestors(node.name):
  657. # get astroid for the searched method
  658. try:
  659. meth_node = overridden[node.name]
  660. except KeyError:
  661. # we have found the method but it's not in the local
  662. # dictionary.
  663. # This may happen with astroid build from living objects
  664. continue
  665. if not isinstance(meth_node, astroid.FunctionDef):
  666. continue
  667. self._check_signature(node, meth_node, 'overridden', klass)
  668. break
  669. if node.decorators:
  670. for decorator in node.decorators.nodes:
  671. if isinstance(decorator, astroid.Attribute) and \
  672. decorator.attrname in ('getter', 'setter', 'deleter'):
  673. # attribute affectation will call this method, not hiding it
  674. return
  675. if isinstance(decorator, astroid.Name) and decorator.name == 'property':
  676. # attribute affectation will either call a setter or raise
  677. # an attribute error, anyway not hiding the function
  678. return
  679. # check if the method is hidden by an attribute
  680. try:
  681. overridden = klass.instance_attr(node.name)[0] # XXX
  682. overridden_frame = overridden.frame()
  683. if (isinstance(overridden_frame, astroid.FunctionDef)
  684. and overridden_frame.type == 'method'):
  685. overridden_frame = overridden_frame.parent.frame()
  686. if (isinstance(overridden_frame, astroid.ClassDef)
  687. and klass.is_subtype_of(overridden_frame.qname())):
  688. args = (overridden.root().name, overridden.fromlineno)
  689. self.add_message('method-hidden', args=args, node=node)
  690. except astroid.NotFoundError:
  691. pass
  692. visit_asyncfunctiondef = visit_functiondef
  693. def _check_useless_super_delegation(self, function):
  694. '''Check if the given function node is an useless method override
  695. We consider it *useless* if it uses the super() builtin, but having
  696. nothing additional whatsoever than not implementing the method at all.
  697. If the method uses super() to delegate an operation to the rest of the MRO,
  698. and if the method called is the same as the current one, the arguments
  699. passed to super() are the same as the parameters that were passed to
  700. this method, then the method could be removed altogether, by letting
  701. other implementation to take precedence.
  702. '''
  703. if not function.is_method():
  704. return
  705. if function.decorators:
  706. # With decorators is a change of use
  707. return
  708. body = function.body
  709. if len(body) != 1:
  710. # Multiple statements, which means this overridden method
  711. # could do multiple things we are not aware of.
  712. return
  713. statement = body[0]
  714. if not isinstance(statement, (astroid.Expr, astroid.Return)):
  715. # Doing something else than what we are interested into.
  716. return
  717. call = statement.value
  718. if not isinstance(call, astroid.Call):
  719. return
  720. if not isinstance(call.func, astroid.Attribute):
  721. # Not a super() attribute access.
  722. return
  723. # Should be a super call.
  724. try:
  725. super_call = next(call.func.expr.infer())
  726. except astroid.InferenceError:
  727. return
  728. else:
  729. if not isinstance(super_call, objects.Super):
  730. return
  731. # The name should be the same.
  732. if call.func.attrname != function.name:
  733. return
  734. # Should be a super call with the MRO pointer being the current class
  735. # and the type being the current instance.
  736. current_scope = function.parent.scope()
  737. if super_call.mro_pointer != current_scope:
  738. return
  739. if not isinstance(super_call.type, astroid.Instance):
  740. return
  741. if super_call.type.name != current_scope.name:
  742. return
  743. # Check values of default args
  744. klass = function.parent.frame()
  745. for overridden in klass.local_attr_ancestors(function.name):
  746. # get astroid for the searched method
  747. try:
  748. meth_node = overridden[function.name]
  749. except KeyError:
  750. # we have found the method but it's not in the local
  751. # dictionary.
  752. # This may happen with astroid build from living objects
  753. continue
  754. if not isinstance(meth_node, astroid.FunctionDef):
  755. # If the method have an ancestor which is not a function
  756. # then it is legitimate to redefine it
  757. return
  758. if _has_different_parameters_default_value(meth_node.args, function.args):
  759. return
  760. else:
  761. break
  762. # Detect if the parameters are the same as the call's arguments.
  763. params = _signature_from_arguments(function.args)
  764. args = _signature_from_call(call)
  765. if _definition_equivalent_to_call(params, args):
  766. self.add_message('useless-super-delegation', node=function,
  767. args=(function.name, ))
  768. def _check_slots(self, node):
  769. if '__slots__' not in node.locals:
  770. return
  771. for slots in node.igetattr('__slots__'):
  772. # check if __slots__ is a valid type
  773. if slots is astroid.YES:
  774. continue
  775. if not is_iterable(slots) and not is_comprehension(slots):
  776. self.add_message('invalid-slots', node=node)
  777. continue
  778. if isinstance(slots, astroid.Const):
  779. # a string, ignore the following checks
  780. self.add_message('single-string-used-for-slots', node=node)
  781. continue
  782. if not hasattr(slots, 'itered'):
  783. # we can't obtain the values, maybe a .deque?
  784. continue
  785. if isinstance(slots, astroid.Dict):
  786. values = [item[0] for item in slots.items]
  787. else:
  788. values = slots.itered()
  789. if values is astroid.YES:
  790. return
  791. for elt in values:
  792. try:
  793. self._check_slots_elt(elt)
  794. except astroid.InferenceError:
  795. continue
  796. def _check_slots_elt(self, elt):
  797. for infered in elt.infer():
  798. if infered is astroid.Uninferable:
  799. continue
  800. if (not isinstance(infered, astroid.Const) or
  801. not isinstance(infered.value, six.string_types)):
  802. self.add_message('invalid-slots-object',
  803. args=infered.as_string(),
  804. node=elt)
  805. continue
  806. if not infered.value:
  807. self.add_message('invalid-slots-object',
  808. args=infered.as_string(),
  809. node=elt)
  810. def leave_functiondef(self, node):
  811. """on method node, check if this method couldn't be a function
  812. ignore class, static and abstract methods, initializer,
  813. methods overridden from a parent class.
  814. """
  815. if node.is_method():
  816. if node.args.args is not None:
  817. self._first_attrs.pop()
  818. if not self.linter.is_message_enabled('no-self-use'):
  819. return
  820. class_node = node.parent.frame()
  821. if (self._meth_could_be_func and node.type == 'method'
  822. and node.name not in PYMETHODS
  823. and not (node.is_abstract() or
  824. overrides_a_method(class_node, node.name) or
  825. decorated_with_property(node) or
  826. (six.PY3 and _has_bare_super_call(node)))):
  827. self.add_message('no-self-use', node=node)
  828. def visit_attribute(self, node):
  829. """check if the getattr is an access to a class member
  830. if so, register it. Also check for access to protected
  831. class member from outside its class (but ignore __special__
  832. methods)
  833. """
  834. # Check self
  835. if self._uses_mandatory_method_param(node):
  836. self._accessed.set_accessed(node)
  837. return
  838. if not self.linter.is_message_enabled('protected-access'):
  839. return
  840. self._check_protected_attribute_access(node)
  841. def visit_assignattr(self, node):
  842. if (isinstance(node.assign_type(), astroid.AugAssign) and
  843. self._uses_mandatory_method_param(node)):
  844. self._accessed.set_accessed(node)
  845. self._check_in_slots(node)
  846. def _check_in_slots(self, node):
  847. """ Check that the given AssignAttr node
  848. is defined in the class slots.
  849. """
  850. infered = safe_infer(node.expr)
  851. if infered and isinstance(infered, astroid.Instance):
  852. klass = infered._proxied
  853. if '__slots__' not in klass.locals or not klass.newstyle:
  854. return
  855. slots = klass.slots()
  856. if slots is None:
  857. return
  858. # If any ancestor doesn't use slots, the slots
  859. # defined for this class are superfluous.
  860. if any('__slots__' not in ancestor.locals and
  861. ancestor.name != 'object'
  862. for ancestor in klass.ancestors()):
  863. return
  864. if not any(slot.value == node.attrname for slot in slots):
  865. # If we have a '__dict__' in slots, then
  866. # assigning any name is valid.
  867. if not any(slot.value == '__dict__' for slot in slots):
  868. if _is_attribute_property(node.attrname, klass):
  869. # Properties circumvent the slots mechanism,
  870. # so we should not emit a warning for them.
  871. return
  872. if (node.attrname in klass.locals
  873. and _has_data_descriptor(klass, node.attrname)):
  874. # Descriptors circumvent the slots mechanism as well.
  875. return
  876. if (node.attrname == '__class__'
  877. and _has_same_layout_slots(slots, node.parent.value)):
  878. return
  879. self.add_message('assigning-non-slot',
  880. args=(node.attrname, ), node=node)
  881. @check_messages('protected-access', 'no-classmethod-decorator',
  882. 'no-staticmethod-decorator')
  883. def visit_assign(self, assign_node):
  884. self._check_classmethod_declaration(assign_node)
  885. node = assign_node.targets[0]
  886. if not isinstance(node, astroid.AssignAttr):
  887. return
  888. if self._uses_mandatory_method_param(node):
  889. return
  890. self._check_protected_attribute_access(node)
  891. def _check_classmethod_declaration(self, node):
  892. """Checks for uses of classmethod() or staticmethod()
  893. When a @classmethod or @staticmethod decorator should be used instead.
  894. A message will be emitted only if the assignment is at a class scope
  895. and only if the classmethod's argument belongs to the class where it
  896. is defined.
  897. `node` is an assign node.
  898. """
  899. if not isinstance(node.value, astroid.Call):
  900. return
  901. # check the function called is "classmethod" or "staticmethod"
  902. func = node.value.func
  903. if (not isinstance(func, astroid.Name) or
  904. func.name not in ('classmethod', 'staticmethod')):
  905. return
  906. msg = ('no-classmethod-decorator' if func.name == 'classmethod' else
  907. 'no-staticmethod-decorator')
  908. # assignment must be at a class scope
  909. parent_class = node.scope()
  910. if not isinstance(parent_class, astroid.ClassDef):
  911. return
  912. # Check if the arg passed to classmethod is a class member
  913. classmeth_arg = node.value.args[0]
  914. if not isinstance(classmeth_arg, astroid.Name):
  915. return
  916. method_name = classmeth_arg.name
  917. if any(method_name == member.name
  918. for member in parent_class.mymethods()):
  919. self.add_message(msg, node=node.targets[0])
  920. def _check_protected_attribute_access(self, node):
  921. '''Given an attribute access node (set or get), check if attribute
  922. access is legitimate. Call _check_first_attr with node before calling
  923. this method. Valid cases are:
  924. * self._attr in a method or cls._attr in a classmethod. Checked by
  925. _check_first_attr.
  926. * Klass._attr inside "Klass" class.
  927. * Klass2._attr inside "Klass" class when Klass2 is a base class of
  928. Klass.
  929. '''
  930. attrname = node.attrname
  931. if (is_attr_protected(attrname) and
  932. attrname not in self.config.exclude_protected):
  933. klass = node_frame_class(node)
  934. # XXX infer to be more safe and less dirty ??
  935. # in classes, check we are not getting a parent method
  936. # through the class object or through super
  937. callee = node.expr.as_string()
  938. # We are not in a class, no remaining valid case
  939. if klass is None:
  940. self.add_message('protected-access', node=node, args=attrname)
  941. return
  942. # If the expression begins with a call to super, that's ok.
  943. if isinstance(node.expr, astroid.Call) and \
  944. isinstance(node.expr.func, astroid.Name) and \
  945. node.expr.func.name == 'super':
  946. return
  947. # If the expression begins with a call to type(self), that's ok.
  948. if self._is_type_self_call(node.expr):
  949. return
  950. # We are in a class, one remaining valid cases, Klass._attr inside
  951. # Klass
  952. if not (callee == klass.name or callee in klass.basenames):
  953. # Detect property assignments in the body of the class.
  954. # This is acceptable:
  955. #
  956. # class A:
  957. # b = property(lambda: self._b)
  958. stmt = node.parent.statement()
  959. if (isinstance(stmt, astroid.Assign)
  960. and len(stmt.targets) == 1
  961. and isinstance(stmt.targets[0], astroid.AssignName)):
  962. name = stmt.targets[0].name
  963. if _is_attribute_property(name, klass):
  964. return
  965. self.add_message('protected-access', node=node, args=attrname)
  966. def _is_type_self_call(self, expr):
  967. return (isinstance(expr, astroid.Call) and
  968. isinstance(expr.func, astroid.Name) and
  969. expr.func.name == 'type' and len(expr.args) == 1 and
  970. self._is_mandatory_method_param(expr.args[0]))
  971. def visit_name(self, node):
  972. """check if the name handle an access to a class member
  973. if so, register it
  974. """
  975. if self._first_attrs and (node.name == self._first_attrs[-1] or
  976. not self._first_attrs[-1]):
  977. self._meth_could_be_func = False
  978. def _check_accessed_members(self, node, accessed):
  979. """check that accessed members are defined"""
  980. # XXX refactor, probably much simpler now that E0201 is in type checker
  981. excs = ('AttributeError', 'Exception', 'BaseException')
  982. for attr, nodes in six.iteritems(accessed):
  983. try:
  984. # is it a class attribute ?
  985. node.local_attr(attr)
  986. # yes, stop here
  987. continue
  988. except astroid.NotFoundError:
  989. pass
  990. # is it an instance attribute of a parent class ?
  991. try:
  992. next(node.instance_attr_ancestors(attr))
  993. # yes, stop here
  994. continue
  995. except StopIteration:
  996. pass
  997. # is it an instance attribute ?
  998. try:
  999. defstmts = node.instance_attr(attr)
  1000. except astroid.NotFoundError:
  1001. pass
  1002. else:
  1003. # filter out augment assignment nodes
  1004. defstmts = [stmt for stmt in defstmts if stmt not in nodes]
  1005. if not defstmts:
  1006. # only augment assignment for this node, no-member should be
  1007. # triggered by the typecheck checker
  1008. continue
  1009. # filter defstmts to only pick the first one when there are
  1010. # several assignments in the same scope
  1011. scope = defstmts[0].scope()
  1012. defstmts = [stmt for i, stmt in enumerate(defstmts)
  1013. if i == 0 or stmt.scope() is not scope]
  1014. # if there are still more than one, don't attempt to be smarter
  1015. # than we can be
  1016. if len(defstmts) == 1:
  1017. defstmt = defstmts[0]
  1018. # check that if the node is accessed in the same method as
  1019. # it's defined, it's accessed after the initial assignment
  1020. frame = defstmt.frame()
  1021. lno = defstmt.fromlineno
  1022. for _node in nodes:
  1023. if _node.frame() is frame and _node.fromlineno < lno \
  1024. and not astroid.are_exclusive(_node.statement(), defstmt, excs):
  1025. self.add_message('access-member-before-definition',
  1026. node=_node, args=(attr, lno))
  1027. def _check_first_arg_for_type(self, node, metaclass=0):
  1028. """check the name of first argument, expect:
  1029. * 'self' for a regular method
  1030. * 'cls' for a class method or a metaclass regular method (actually
  1031. valid-classmethod-first-arg value)
  1032. * 'mcs' for a metaclass class method (actually
  1033. valid-metaclass-classmethod-first-arg)
  1034. * not one of the above for a static method
  1035. """
  1036. # don't care about functions with unknown argument (builtins)
  1037. if node.args.args is None:
  1038. return
  1039. first_arg = node.args.args and node.argnames()[0]
  1040. self._first_attrs.append(first_arg)
  1041. first = self._first_attrs[-1]
  1042. # static method
  1043. if node.type == 'staticmethod':
  1044. if (first_arg == 'self' or
  1045. first_arg in self.config.valid_classmethod_first_arg or
  1046. first_arg in self.config.valid_metaclass_classmethod_first_arg):
  1047. self.add_message('bad-staticmethod-argument', args=first, node=node)
  1048. return
  1049. self._first_attrs[-1] = None
  1050. # class / regular method with no args
  1051. elif not node.args.args:
  1052. self.add_message('no-method-argument', node=node)
  1053. # metaclass
  1054. elif metaclass:
  1055. # metaclass __new__ or classmethod
  1056. if node.type == 'classmethod':
  1057. self._check_first_arg_config(
  1058. first,
  1059. self.config.valid_metaclass_classmethod_first_arg, node,
  1060. 'bad-mcs-classmethod-argument', node.name)
  1061. # metaclass regular method
  1062. else:
  1063. self._check_first_arg_config(
  1064. first,
  1065. self.config.valid_classmethod_first_arg, node,
  1066. 'bad-mcs-method-argument',
  1067. node.name)
  1068. # regular class
  1069. else:
  1070. # class method
  1071. if node.type == 'classmethod':
  1072. self._check_first_arg_config(
  1073. first,
  1074. self.config.valid_classmethod_first_arg, node,
  1075. 'bad-classmethod-argument',
  1076. node.name)
  1077. # regular method without self as argument
  1078. elif first != 'self':
  1079. self.add_message('no-self-argument', node=node)
  1080. def _check_first_arg_config(self, first, config, node, message,
  1081. method_name):
  1082. if first not in config:
  1083. if len(config) == 1:
  1084. valid = repr(config[0])
  1085. else:
  1086. valid = ', '.join(repr(v) for v in config[:-1])
  1087. valid = '%s or %r' % (valid, config[-1])
  1088. self.add_message(message, args=(method_name, valid), node=node)
  1089. def _check_bases_classes(self, node):
  1090. """check that the given class node implements abstract methods from
  1091. base classes
  1092. """
  1093. def is_abstract(method):
  1094. return method.is_abstract(pass_is_abstract=False)
  1095. # check if this class abstract
  1096. if class_is_abstract(node):
  1097. return
  1098. methods = sorted(
  1099. unimplemented_abstract_methods(node, is_abstract).items(),
  1100. key=lambda item: item[0],
  1101. )
  1102. for name, method in methods:
  1103. owner = method.parent.frame()
  1104. if owner is node:
  1105. continue
  1106. # owner is not this class, it must be a parent class
  1107. # check that the ancestor's method is not abstract
  1108. if name in node.locals:
  1109. # it is redefined as an attribute or with a descriptor
  1110. continue
  1111. self.add_message('abstract-method', node=node,
  1112. args=(name, owner.name))
  1113. def _check_init(self, node):
  1114. """check that the __init__ method call super or ancestors'__init__
  1115. method
  1116. """
  1117. if (not self.linter.is_message_enabled('super-init-not-called') and
  1118. not self.linter.is_message_enabled('non-parent-init-called')):
  1119. return
  1120. klass_node = node.parent.frame()
  1121. to_call = _ancestors_to_call(klass_node)
  1122. not_called_yet = dict(to_call)
  1123. for stmt in node.nodes_of_class(astroid.Call):
  1124. expr = stmt.func
  1125. if not isinstance(expr, astroid.Attribute) \
  1126. or expr.attrname != '__init__':
  1127. continue
  1128. # skip the test if using super
  1129. if isinstance(expr.expr, astroid.Call) and \
  1130. isinstance(expr.expr.func, astroid.Name) and \
  1131. expr.expr.func.name == 'super':
  1132. return
  1133. try:
  1134. for klass in expr.expr.infer():
  1135. if klass is astroid.Uninferable:
  1136. continue
  1137. # The infered klass can be super(), which was
  1138. # assigned to a variable and the `__init__`
  1139. # was called later.
  1140. #
  1141. # base = super()
  1142. # base.__init__(...)
  1143. if (isinstance(klass, astroid.Instance) and
  1144. isinstance(klass._proxied, astroid.ClassDef) and
  1145. is_builtin_object(klass._proxied) and
  1146. klass._proxied.name == 'super'):
  1147. return
  1148. elif isinstance(klass, objects.Super):
  1149. return
  1150. try:
  1151. del not_called_yet[klass]
  1152. except KeyError:
  1153. if klass not in to_call:
  1154. self.add_message('non-parent-init-called',
  1155. node=expr, args=klass.name)
  1156. except astroid.InferenceError:
  1157. continue
  1158. for klass, method in six.iteritems(not_called_yet):
  1159. cls = node_frame_class(method)
  1160. if klass.name == 'object' or (cls and cls.name == 'object'):
  1161. continue
  1162. self.add_message('super-init-not-called', args=klass.name, node=node)
  1163. def _check_signature(self, method1, refmethod, class_type, cls):
  1164. """check that the signature of the two given methods match
  1165. """
  1166. if not (isinstance(method1, astroid.FunctionDef)
  1167. and isinstance(refmethod, astroid.FunctionDef)):
  1168. self.add_message('method-check-failed',
  1169. args=(method1, refmethod), node=method1)
  1170. return
  1171. instance = cls.instantiate_class()
  1172. method1 = function_to_method(method1, instance)
  1173. refmethod = function_to_method(refmethod, instance)
  1174. # Don't care about functions with unknown argument (builtins).
  1175. if method1.args.args is None or refmethod.args.args is None:
  1176. return
  1177. # Ignore private to class methods.
  1178. if is_attr_private(method1.name):
  1179. return
  1180. # Ignore setters, they have an implicit extra argument,
  1181. # which shouldn't be taken in consideration.
  1182. if method1.decorators:
  1183. for decorator in method1.decorators.nodes:
  1184. if (isinstance(decorator, astroid.Attribute) and
  1185. decorator.attrname == 'setter'):
  1186. return
  1187. if _different_parameters(
  1188. refmethod, method1,
  1189. dummy_parameter_regex=self._dummy_rgx):
  1190. self.add_message('arguments-differ',
  1191. args=(class_type, method1.name),
  1192. node=method1)
  1193. elif len(method1.args.defaults) < len(refmethod.args.defaults):
  1194. self.add_message('signature-differs',
  1195. args=(class_type, method1.name),
  1196. node=method1)
  1197. def _uses_mandatory_method_param(self, node):
  1198. """Check that attribute lookup name use first attribute variable name
  1199. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
  1200. """
  1201. return self._is_mandatory_method_param(node.expr)
  1202. def _is_mandatory_method_param(self, node):
  1203. """Check if astroid.Name corresponds to first attribute variable name
  1204. Name is `self` for method, `cls` for classmethod and `mcs` for metaclass.
  1205. """
  1206. return (self._first_attrs and isinstance(node, astroid.Name)
  1207. and node.name == self._first_attrs[-1])
  1208. class SpecialMethodsChecker(BaseChecker):
  1209. """Checker which verifies that special methods
  1210. are implemented correctly.
  1211. """
  1212. __implements__ = (IAstroidChecker, )
  1213. name = 'classes'
  1214. msgs = {
  1215. 'E0301': ('__iter__ returns non-iterator',
  1216. 'non-iterator-returned',
  1217. 'Used when an __iter__ method returns something which is not an '
  1218. 'iterable (i.e. has no `%s` method)' % NEXT_METHOD,
  1219. {'old_names': [('W0234', 'non-iterator-returned'),
  1220. ('E0234', 'non-iterator-returned')]}),
  1221. 'E0302': ('The special method %r expects %s param(s), %d %s given',
  1222. 'unexpected-special-method-signature',
  1223. 'Emitted when a special method was defined with an '
  1224. 'invalid number of parameters. If it has too few or '
  1225. 'too many, it might not work at all.',
  1226. {'old_names': [('E0235', 'bad-context-manager')]}),
  1227. 'E0303': ('__len__ does not return non-negative integer',
  1228. 'invalid-length-returned',
  1229. 'Used when an __len__ method returns something which is not a '
  1230. 'non-negative integer', {}),
  1231. }
  1232. priority = -2
  1233. @check_messages('unexpected-special-method-signature',
  1234. 'non-iterator-returned', 'invalid-length-returned')
  1235. def visit_functiondef(self, node):
  1236. if not node.is_method():
  1237. return
  1238. if node.name == '__iter__':
  1239. self._check_iter(node)
  1240. if node.name == '__len__':
  1241. self._check_len(node)
  1242. if node.name in PYMETHODS:
  1243. self._check_unexpected_method_signature(node)
  1244. visit_asyncfunctiondef = visit_functiondef
  1245. def _check_unexpected_method_signature(self, node):
  1246. expected_params = SPECIAL_METHODS_PARAMS[node.name]
  1247. if expected_params is None:
  1248. # This can support a variable number of parameters.
  1249. return
  1250. if not node.args.args and not node.args.vararg:
  1251. # Method has no parameter, will be caught
  1252. # by no-method-argument.
  1253. return
  1254. if decorated_with(node, [BUILTINS + ".staticmethod"]):
  1255. # We expect to not take in consideration self.
  1256. all_args = node.args.args
  1257. else:
  1258. all_args = node.args.args[1:]
  1259. mandatory = len(all_args) - len(node.args.defaults)
  1260. optional = len(node.args.defaults)
  1261. current_params = mandatory + optional
  1262. if isinstance(expected_params, tuple):
  1263. # The expected number of parameters can be any value from this
  1264. # tuple, although the user should implement the method
  1265. # to take all of them in consideration.
  1266. emit = mandatory not in expected_params
  1267. expected_params = "between %d or %d" % expected_params
  1268. else:
  1269. # If the number of mandatory parameters doesn't
  1270. # suffice, the expected parameters for this
  1271. # function will be deduced from the optional
  1272. # parameters.
  1273. rest = expected_params - mandatory
  1274. if rest == 0:
  1275. emit = False
  1276. elif rest < 0:
  1277. emit = True
  1278. elif rest > 0:
  1279. emit = not ((optional - rest) >= 0 or node.args.vararg)
  1280. if emit:
  1281. verb = "was" if current_params <= 1 else "were"
  1282. self.add_message('unexpected-special-method-signature',
  1283. args=(node.name, expected_params, current_params, verb),
  1284. node=node)
  1285. @staticmethod
  1286. def _is_iterator(node):
  1287. if node is astroid.YES:
  1288. # Just ignore YES objects.
  1289. return True
  1290. if isinstance(node, Generator):
  1291. # Generators can be itered.
  1292. return True
  1293. if isinstance(node, astroid.Instance):
  1294. try:
  1295. node.local_attr(NEXT_METHOD)
  1296. return True
  1297. except astroid.NotFoundError:
  1298. pass
  1299. elif isinstance(node, astroid.ClassDef):
  1300. metaclass = node.metaclass()
  1301. if metaclass and isinstance(metaclass, astroid.ClassDef):
  1302. try:
  1303. metaclass.local_attr(NEXT_METHOD)
  1304. return True
  1305. except astroid.NotFoundError:
  1306. pass
  1307. return False
  1308. def _check_iter(self, node):
  1309. infered = _safe_infer_call_result(node, node)
  1310. if infered is not None:
  1311. if not self._is_iterator(infered):
  1312. self.add_message('non-iterator-returned', node=node)
  1313. def _check_len(self, node):
  1314. inferred = _safe_infer_call_result(node, node)
  1315. if not inferred or inferred is astroid.Uninferable:
  1316. return
  1317. if (isinstance(inferred, astroid.Instance)
  1318. and inferred.name == 'int'
  1319. and not isinstance(inferred, astroid.Const)):
  1320. # Assume it's good enough, since the int() call might wrap
  1321. # something that's uninferable for us
  1322. return
  1323. if not isinstance(inferred, astroid.Const):
  1324. self.add_message('invalid-length-returned', node=node)
  1325. return
  1326. value = inferred.value
  1327. if not isinstance(value, six.integer_types) or value < 0:
  1328. self.add_message('invalid-length-returned', node=node)
  1329. def _ancestors_to_call(klass_node, method='__init__'):
  1330. """return a dictionary where keys are the list of base classes providing
  1331. the queried method, and so that should/may be called from the method node
  1332. """
  1333. to_call = {}
  1334. for base_node in klass_node.ancestors(recurs=False):
  1335. try:
  1336. to_call[base_node] = next(base_node.igetattr(method))
  1337. except astroid.InferenceError:
  1338. continue
  1339. return to_call
  1340. def node_method(node, method_name):
  1341. """get astroid for <method_name> on the given class node, ensuring it
  1342. is a Function node
  1343. """
  1344. for node_attr in node.local_attr(method_name):
  1345. if isinstance(node_attr, astroid.Function):
  1346. return node_attr
  1347. raise astroid.NotFoundError(method_name)
  1348. def register(linter):
  1349. """required method to auto register this checker """
  1350. linter.register_checker(ClassChecker(linter))
  1351. linter.register_checker(SpecialMethodsChecker(linter))