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.

base.py 77KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2010 Daniel Harding <dharding@gmail.com>
  4. # Copyright (c) 2012-2014 Google, Inc.
  5. # Copyright (c) 2013-2017 Claudiu Popa <pcmanticore@gmail.com>
  6. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  7. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  8. # Copyright (c) 2015 Nick Bastin <nick.bastin@gmail.com>
  9. # Copyright (c) 2015 Michael Kefeder <oss@multiwave.ch>
  10. # Copyright (c) 2015 Dmitry Pribysh <dmand@yandex.ru>
  11. # Copyright (c) 2015 Stephane Wirtel <stephane@wirtel.be>
  12. # Copyright (c) 2015 Cosmin Poieana <cmin@ropython.org>
  13. # Copyright (c) 2015 Florian Bruhin <me@the-compiler.org>
  14. # Copyright (c) 2015 Radu Ciorba <radu@devrandom.ro>
  15. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  16. # Copyright (c) 2016-2017 Łukasz Rogalski <rogalski.91@gmail.com>
  17. # Copyright (c) 2016 Glenn Matthews <glenn@e-dad.net>
  18. # Copyright (c) 2016 Elias Dorneles <eliasdorneles@gmail.com>
  19. # Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk>
  20. # Copyright (c) 2016 Yannack <yannack@users.noreply.github.com>
  21. # Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net>
  22. # Copyright (c) 2016 Alex Jurkiewicz <alex@jurkiewi.cz>
  23. # Copyright (c) 2017 Jacques Kvam <jwkvam@gmail.com>
  24. # Copyright (c) 2017 ttenhoeve-aa <ttenhoeve@appannie.com>
  25. # Copyright (c) 2017 hippo91 <guillaume.peillex@gmail.com>
  26. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  27. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  28. """basic checker for Python code"""
  29. import collections
  30. import itertools
  31. import sys
  32. import re
  33. import six
  34. from six.moves import zip # pylint: disable=redefined-builtin
  35. import astroid
  36. import astroid.bases
  37. import astroid.scoped_nodes
  38. from pylint import checkers
  39. from pylint import exceptions
  40. from pylint import interfaces
  41. from pylint.checkers import utils
  42. from pylint import reporters
  43. from pylint.checkers.utils import get_node_last_lineno
  44. from pylint.reporters.ureports import nodes as reporter_nodes
  45. import pylint.utils as lint_utils
  46. class NamingStyle(object):
  47. # It may seem counterintuitive that single naming style
  48. # has multiple "accepted" forms of regular expressions,
  49. # but we need to special-case stuff like dunder names
  50. # in method names.
  51. CLASS_NAME_RGX = None
  52. MOD_NAME_RGX = None
  53. CONST_NAME_RGX = None
  54. COMP_VAR_RGX = None
  55. DEFAULT_NAME_RGX = None
  56. CLASS_ATTRIBUTE_RGX = None
  57. @classmethod
  58. def get_regex(cls, name_type):
  59. return {
  60. 'module': cls.MOD_NAME_RGX,
  61. 'const': cls.CONST_NAME_RGX,
  62. 'class': cls.CLASS_NAME_RGX,
  63. 'function': cls.DEFAULT_NAME_RGX,
  64. 'method': cls.DEFAULT_NAME_RGX,
  65. 'attr': cls.DEFAULT_NAME_RGX,
  66. 'argument': cls.DEFAULT_NAME_RGX,
  67. 'variable': cls.DEFAULT_NAME_RGX,
  68. 'class_attribute': cls.CLASS_ATTRIBUTE_RGX,
  69. 'inlinevar': cls.COMP_VAR_RGX,
  70. }[name_type]
  71. class SnakeCaseStyle(NamingStyle):
  72. CLASS_NAME_RGX = re.compile('[a-z_][a-z0-9_]+$')
  73. MOD_NAME_RGX = re.compile('([a-z_][a-z0-9_]*)$')
  74. CONST_NAME_RGX = re.compile('(([a-z_][a-z0-9_]*)|(__.*__))$')
  75. COMP_VAR_RGX = re.compile('[a-z_][a-z0-9_]*$')
  76. DEFAULT_NAME_RGX = re.compile('(([a-z_][a-z0-9_]{2,30})|(_[a-z0-9_]*)|(__[a-z][a-z0-9_]+__))$')
  77. CLASS_ATTRIBUTE_RGX = re.compile(r'(([a-z_][a-z0-9_]{2,30}|(__.*__)))$')
  78. class CamelCaseStyle(NamingStyle):
  79. CLASS_NAME_RGX = re.compile('[a-z_][a-zA-Z0-9]+$')
  80. MOD_NAME_RGX = re.compile('([a-z_][a-zA-Z0-9]*)$')
  81. CONST_NAME_RGX = re.compile('(([a-z_][A-Za-z0-9]*)|(__.*__))$')
  82. COMP_VAR_RGX = re.compile('[a-z_][A-Za-z0-9]*$')
  83. DEFAULT_NAME_RGX = re.compile('(([a-z_][a-zA-Z0-9]{2,30})|(__[a-z][a-zA-Z0-9_]+__))$')
  84. CLASS_ATTRIBUTE_RGX = re.compile(r'([a-z_][A-Za-z0-9]{2,30}|(__.*__))$')
  85. class PascalCaseStyle(NamingStyle):
  86. CLASS_NAME_RGX = re.compile('[A-Z_][a-zA-Z0-9]+$')
  87. MOD_NAME_RGX = re.compile('[A-Z_][a-zA-Z0-9]+$')
  88. CONST_NAME_RGX = re.compile('(([A-Z_][A-Za-z0-9]*)|(__.*__))$')
  89. COMP_VAR_RGX = re.compile('[A-Z_][a-zA-Z0-9]+$')
  90. DEFAULT_NAME_RGX = re.compile('[A-Z_][a-zA-Z0-9]{2,30}$|(__[a-z][a-zA-Z0-9_]+__)$')
  91. CLASS_ATTRIBUTE_RGX = re.compile('[A-Z_][a-zA-Z0-9]{2,30}$')
  92. class UpperCaseStyle(NamingStyle):
  93. CLASS_NAME_RGX = re.compile('[A-Z_][A-Z0-9_]+$')
  94. MOD_NAME_RGX = re.compile('[A-Z_][A-Z0-9_]+$')
  95. CONST_NAME_RGX = re.compile('(([A-Z_][A-Z0-9_]*)|(__.*__))$')
  96. COMP_VAR_RGX = re.compile('[A-Z_][A-Z0-9_]+$')
  97. DEFAULT_NAME_RGX = re.compile('([A-Z_][A-Z0-9_]{2,30})|(__[a-z][a-zA-Z0-9_]+__)$')
  98. CLASS_ATTRIBUTE_RGX = re.compile('[A-Z_][A-Z0-9_]{2,30}$')
  99. class AnyStyle(NamingStyle):
  100. @classmethod
  101. def get_regex(cls, name_type):
  102. return re.compile('.*')
  103. NAMING_STYLES = {'snake_case': SnakeCaseStyle, 'camelCase': CamelCaseStyle,
  104. 'PascalCase': PascalCaseStyle, 'UPPER_CASE': UpperCaseStyle,
  105. 'any': AnyStyle}
  106. # do not require a doc string on private/system methods
  107. NO_REQUIRED_DOC_RGX = re.compile('^_')
  108. REVERSED_PROTOCOL_METHOD = '__reversed__'
  109. SEQUENCE_PROTOCOL_METHODS = ('__getitem__', '__len__')
  110. REVERSED_METHODS = (SEQUENCE_PROTOCOL_METHODS,
  111. (REVERSED_PROTOCOL_METHOD, ))
  112. TYPECHECK_COMPARISON_OPERATORS = frozenset(('is', 'is not', '==',
  113. '!=', 'in', 'not in'))
  114. LITERAL_NODE_TYPES = (astroid.Const, astroid.Dict, astroid.List, astroid.Set)
  115. UNITTEST_CASE = 'unittest.case'
  116. BUILTINS = six.moves.builtins.__name__
  117. TYPE_QNAME = "%s.type" % BUILTINS
  118. PY33 = sys.version_info >= (3, 3)
  119. PY3K = sys.version_info >= (3, 0)
  120. PY35 = sys.version_info >= (3, 5)
  121. # Name categories that are always consistent with all naming conventions.
  122. EXEMPT_NAME_CATEGORIES = {'exempt', 'ignore'}
  123. # A mapping from builtin-qname -> symbol, to be used when generating messages
  124. # about dangerous default values as arguments
  125. DEFAULT_ARGUMENT_SYMBOLS = dict(
  126. zip(['.'.join([BUILTINS, x]) for x in ('set', 'dict', 'list')],
  127. ['set()', '{}', '[]'])
  128. )
  129. REVERSED_COMPS = {'<': '>', '<=': '>=', '>': '<', '>=': '<='}
  130. def _redefines_import(node):
  131. """ Detect that the given node (AssignName) is inside an
  132. exception handler and redefines an import from the tryexcept body.
  133. Returns True if the node redefines an import, False otherwise.
  134. """
  135. current = node
  136. while current and not isinstance(current.parent, astroid.ExceptHandler):
  137. current = current.parent
  138. if not current or not utils.error_of_type(current.parent, ImportError):
  139. return False
  140. try_block = current.parent.parent
  141. for import_node in try_block.nodes_of_class((astroid.ImportFrom, astroid.Import)):
  142. for name, alias in import_node.names:
  143. if alias:
  144. if alias == node.name:
  145. return True
  146. elif name == node.name:
  147. return True
  148. return False
  149. def in_loop(node):
  150. """return True if the node is inside a kind of for loop"""
  151. parent = node.parent
  152. while parent is not None:
  153. if isinstance(parent, (astroid.For, astroid.ListComp, astroid.SetComp,
  154. astroid.DictComp, astroid.GeneratorExp)):
  155. return True
  156. parent = parent.parent
  157. return False
  158. def in_nested_list(nested_list, obj):
  159. """return true if the object is an element of <nested_list> or of a nested
  160. list
  161. """
  162. for elmt in nested_list:
  163. if isinstance(elmt, (list, tuple)):
  164. if in_nested_list(elmt, obj):
  165. return True
  166. elif elmt == obj:
  167. return True
  168. return False
  169. def _get_break_loop_node(break_node):
  170. """
  171. Returns the loop node that holds the break node in arguments.
  172. Args:
  173. break_node (astroid.Break): the break node of interest.
  174. Returns:
  175. astroid.For or astroid.While: the loop node holding the break node.
  176. """
  177. loop_nodes = (astroid.For, astroid.While)
  178. parent = break_node.parent
  179. while not isinstance(parent, loop_nodes) or break_node in getattr(parent, 'orelse', []):
  180. parent = parent.parent
  181. if parent is None:
  182. break
  183. return parent
  184. def _loop_exits_early(loop):
  185. """
  186. Returns true if a loop may ends up in a break statement.
  187. Args:
  188. loop (astroid.For, astroid.While): the loop node inspected.
  189. Returns:
  190. bool: True if the loop may ends up in a break statement, False otherwise.
  191. """
  192. loop_nodes = (astroid.For, astroid.While)
  193. definition_nodes = (astroid.FunctionDef, astroid.ClassDef)
  194. inner_loop_nodes = [
  195. _node for _node in loop.nodes_of_class(loop_nodes,
  196. skip_klass=definition_nodes)
  197. if _node != loop
  198. ]
  199. return any(
  200. _node for _node in loop.nodes_of_class(astroid.Break,
  201. skip_klass=definition_nodes)
  202. if _get_break_loop_node(_node) not in inner_loop_nodes
  203. )
  204. def _is_multi_naming_match(match, node_type, confidence):
  205. return (match is not None and
  206. match.lastgroup is not None and
  207. match.lastgroup not in EXEMPT_NAME_CATEGORIES
  208. and (node_type != 'method' or confidence != interfaces.INFERENCE_FAILURE))
  209. if sys.version_info < (3, 0):
  210. BUILTIN_PROPERTY = '__builtin__.property'
  211. else:
  212. BUILTIN_PROPERTY = 'builtins.property'
  213. def _get_properties(config):
  214. """Returns a tuple of property classes and names.
  215. Property classes are fully qualified, such as 'abc.abstractproperty' and
  216. property names are the actual names, such as 'abstract_property'.
  217. """
  218. property_classes = set((BUILTIN_PROPERTY,))
  219. property_names = set() # Not returning 'property', it has its own check.
  220. if config is not None:
  221. property_classes.update(config.property_classes)
  222. property_names.update((prop.rsplit('.', 1)[-1]
  223. for prop in config.property_classes))
  224. return property_classes, property_names
  225. def _determine_function_name_type(node, config=None):
  226. """Determine the name type whose regex the a function's name should match.
  227. :param node: A function node.
  228. :type node: astroid.node_classes.NodeNG
  229. :param config: Configuration from which to pull additional property classes.
  230. :type config: :class:`optparse.Values`
  231. :returns: One of ('function', 'method', 'attr')
  232. :rtype: str
  233. """
  234. property_classes, property_names = _get_properties(config)
  235. if not node.is_method():
  236. return 'function'
  237. if node.decorators:
  238. decorators = node.decorators.nodes
  239. else:
  240. decorators = []
  241. for decorator in decorators:
  242. # If the function is a property (decorated with @property
  243. # or @abc.abstractproperty), the name type is 'attr'.
  244. if (isinstance(decorator, astroid.Name) or
  245. (isinstance(decorator, astroid.Attribute) and
  246. decorator.attrname in property_names)):
  247. infered = utils.safe_infer(decorator)
  248. if infered and infered.qname() in property_classes:
  249. return 'attr'
  250. # If the function is decorated using the prop_method.{setter,getter}
  251. # form, treat it like an attribute as well.
  252. elif (isinstance(decorator, astroid.Attribute) and
  253. decorator.attrname in ('setter', 'deleter')):
  254. return 'attr'
  255. return 'method'
  256. def _has_abstract_methods(node):
  257. """
  258. Determine if the given `node` has abstract methods.
  259. The methods should be made abstract by decorating them
  260. with `abc` decorators.
  261. """
  262. return len(utils.unimplemented_abstract_methods(node)) > 0
  263. def report_by_type_stats(sect, stats, old_stats):
  264. """make a report of
  265. * percentage of different types documented
  266. * percentage of different types with a bad name
  267. """
  268. # percentage of different types documented and/or with a bad name
  269. nice_stats = {}
  270. for node_type in ('module', 'class', 'method', 'function'):
  271. try:
  272. total = stats[node_type]
  273. except KeyError:
  274. raise exceptions.EmptyReportError()
  275. nice_stats[node_type] = {}
  276. if total != 0:
  277. try:
  278. documented = total - stats['undocumented_'+node_type]
  279. percent = (documented * 100.) / total
  280. nice_stats[node_type]['percent_documented'] = '%.2f' % percent
  281. except KeyError:
  282. nice_stats[node_type]['percent_documented'] = 'NC'
  283. try:
  284. percent = (stats['badname_'+node_type] * 100.) / total
  285. nice_stats[node_type]['percent_badname'] = '%.2f' % percent
  286. except KeyError:
  287. nice_stats[node_type]['percent_badname'] = 'NC'
  288. lines = ('type', 'number', 'old number', 'difference',
  289. '%documented', '%badname')
  290. for node_type in ('module', 'class', 'method', 'function'):
  291. new = stats[node_type]
  292. old = old_stats.get(node_type, None)
  293. if old is not None:
  294. diff_str = reporters.diff_string(old, new)
  295. else:
  296. old, diff_str = 'NC', 'NC'
  297. lines += (node_type, str(new), str(old), diff_str,
  298. nice_stats[node_type].get('percent_documented', '0'),
  299. nice_stats[node_type].get('percent_badname', '0'))
  300. sect.append(reporter_nodes.Table(children=lines, cols=6, rheaders=1))
  301. def redefined_by_decorator(node):
  302. """return True if the object is a method redefined via decorator.
  303. For example:
  304. @property
  305. def x(self): return self._x
  306. @x.setter
  307. def x(self, value): self._x = value
  308. """
  309. if node.decorators:
  310. for decorator in node.decorators.nodes:
  311. if (isinstance(decorator, astroid.Attribute) and
  312. getattr(decorator.expr, 'name', None) == node.name):
  313. return True
  314. return False
  315. class _BasicChecker(checkers.BaseChecker):
  316. __implements__ = interfaces.IAstroidChecker
  317. name = 'basic'
  318. class BasicErrorChecker(_BasicChecker):
  319. msgs = {
  320. 'E0100': ('__init__ method is a generator',
  321. 'init-is-generator',
  322. 'Used when the special class method __init__ is turned into a '
  323. 'generator by a yield in its body.'),
  324. 'E0101': ('Explicit return in __init__',
  325. 'return-in-init',
  326. 'Used when the special class method __init__ has an explicit '
  327. 'return value.'),
  328. 'E0102': ('%s already defined line %s',
  329. 'function-redefined',
  330. 'Used when a function / class / method is redefined.'),
  331. 'E0103': ('%r not properly in loop',
  332. 'not-in-loop',
  333. 'Used when break or continue keywords are used outside a loop.'),
  334. 'E0104': ('Return outside function',
  335. 'return-outside-function',
  336. 'Used when a "return" statement is found outside a function or '
  337. 'method.'),
  338. 'E0105': ('Yield outside function',
  339. 'yield-outside-function',
  340. 'Used when a "yield" statement is found outside a function or '
  341. 'method.'),
  342. 'E0106': ('Return with argument inside generator',
  343. 'return-arg-in-generator',
  344. 'Used when a "return" statement with an argument is found '
  345. 'outside in a generator function or method (e.g. with some '
  346. '"yield" statements).',
  347. {'maxversion': (3, 3)}),
  348. 'E0107': ("Use of the non-existent %s operator",
  349. 'nonexistent-operator',
  350. "Used when you attempt to use the C-style pre-increment or"
  351. "pre-decrement operator -- and ++, which doesn't exist in Python."),
  352. 'E0108': ('Duplicate argument name %s in function definition',
  353. 'duplicate-argument-name',
  354. 'Duplicate argument names in function definitions are syntax'
  355. ' errors.'),
  356. 'E0110': ('Abstract class %r with abstract methods instantiated',
  357. 'abstract-class-instantiated',
  358. 'Used when an abstract class with `abc.ABCMeta` as metaclass '
  359. 'has abstract methods and is instantiated.'),
  360. 'W0120': ('Else clause on loop without a break statement',
  361. 'useless-else-on-loop',
  362. 'Loops should only have an else clause if they can exit early '
  363. 'with a break statement, otherwise the statements under else '
  364. 'should be on the same scope as the loop itself.'),
  365. 'E0112': ('More than one starred expression in assignment',
  366. 'too-many-star-expressions',
  367. 'Emitted when there are more than one starred '
  368. 'expressions (`*x`) in an assignment. This is a SyntaxError.',
  369. {'minversion': (3, 0)}),
  370. 'E0113': ('Starred assignment target must be in a list or tuple',
  371. 'invalid-star-assignment-target',
  372. 'Emitted when a star expression is used as a starred '
  373. 'assignment target.',
  374. {'minversion': (3, 0)}),
  375. 'E0114': ('Can use starred expression only in assignment target',
  376. 'star-needs-assignment-target',
  377. 'Emitted when a star expression is not used in an '
  378. 'assignment target.',
  379. {'minversion': (3, 0)}),
  380. 'E0115': ('Name %r is nonlocal and global',
  381. 'nonlocal-and-global',
  382. 'Emitted when a name is both nonlocal and global.',
  383. {'minversion': (3, 0)}),
  384. 'E0116': ("'continue' not supported inside 'finally' clause",
  385. 'continue-in-finally',
  386. 'Emitted when the `continue` keyword is found '
  387. 'inside a finally clause, which is a SyntaxError.'),
  388. 'E0117': ("nonlocal name %s found without binding",
  389. 'nonlocal-without-binding',
  390. 'Emitted when a nonlocal variable does not have an attached '
  391. 'name somewhere in the parent scopes',
  392. {'minversion': (3, 0)}),
  393. 'E0118': ("Name %r is used prior to global declaration",
  394. 'used-prior-global-declaration',
  395. 'Emitted when a name is used prior a global declaration, '
  396. 'which results in an error since Python 3.6.',
  397. {'minversion': (3, 6)}),
  398. }
  399. @utils.check_messages('function-redefined')
  400. def visit_classdef(self, node):
  401. self._check_redefinition('class', node)
  402. @utils.check_messages('too-many-star-expressions',
  403. 'invalid-star-assignment-target')
  404. def visit_assign(self, node):
  405. starred = list(node.targets[0].nodes_of_class(astroid.Starred))
  406. if len(starred) > 1:
  407. self.add_message('too-many-star-expressions', node=node)
  408. # Check *a = b
  409. if isinstance(node.targets[0], astroid.Starred):
  410. self.add_message('invalid-star-assignment-target', node=node)
  411. @utils.check_messages('star-needs-assignment-target')
  412. def visit_starred(self, node):
  413. """Check that a Starred expression is used in an assignment target."""
  414. if isinstance(node.parent, astroid.Call):
  415. # f(*args) is converted to Call(args=[Starred]), so ignore
  416. # them for this check.
  417. return
  418. if PY35 and isinstance(node.parent,
  419. (astroid.List, astroid.Tuple,
  420. astroid.Set, astroid.Dict)):
  421. # PEP 448 unpacking.
  422. return
  423. stmt = node.statement()
  424. if not isinstance(stmt, astroid.Assign):
  425. return
  426. if stmt.value is node or stmt.value.parent_of(node):
  427. self.add_message('star-needs-assignment-target', node=node)
  428. @utils.check_messages('init-is-generator', 'return-in-init',
  429. 'function-redefined', 'return-arg-in-generator',
  430. 'duplicate-argument-name', 'nonlocal-and-global',
  431. 'used-prior-global-declaration')
  432. def visit_functiondef(self, node):
  433. self._check_nonlocal_and_global(node)
  434. self._check_name_used_prior_global(node)
  435. if (not redefined_by_decorator(node) and
  436. not utils.is_registered_in_singledispatch_function(node)):
  437. self._check_redefinition(node.is_method() and 'method' or 'function', node)
  438. # checks for max returns, branch, return in __init__
  439. returns = node.nodes_of_class(astroid.Return,
  440. skip_klass=(astroid.FunctionDef,
  441. astroid.ClassDef))
  442. if node.is_method() and node.name == '__init__':
  443. if node.is_generator():
  444. self.add_message('init-is-generator', node=node)
  445. else:
  446. values = [r.value for r in returns]
  447. # Are we returning anything but None from constructors
  448. if any(v for v in values if not utils.is_none(v)):
  449. self.add_message('return-in-init', node=node)
  450. elif node.is_generator():
  451. # make sure we don't mix non-None returns and yields
  452. if not PY33:
  453. for retnode in returns:
  454. if isinstance(retnode.value, astroid.Const) and \
  455. retnode.value.value is not None:
  456. self.add_message('return-arg-in-generator', node=node,
  457. line=retnode.fromlineno)
  458. # Check for duplicate names
  459. args = set()
  460. for name in node.argnames():
  461. if name in args:
  462. self.add_message('duplicate-argument-name', node=node, args=(name,))
  463. else:
  464. args.add(name)
  465. visit_asyncfunctiondef = visit_functiondef
  466. def _check_name_used_prior_global(self, node):
  467. scope_globals = {
  468. name: child
  469. for child in node.nodes_of_class(astroid.Global)
  470. for name in child.names
  471. if child.scope() is node
  472. }
  473. for node_name in node.nodes_of_class(astroid.Name):
  474. if node_name.scope() is not node:
  475. continue
  476. name = node_name.name
  477. corresponding_global = scope_globals.get(name)
  478. if not corresponding_global:
  479. continue
  480. global_lineno = corresponding_global.fromlineno
  481. if global_lineno and global_lineno > node_name.fromlineno:
  482. self.add_message('used-prior-global-declaration',
  483. node=node_name, args=(name, ))
  484. def _check_nonlocal_and_global(self, node):
  485. """Check that a name is both nonlocal and global."""
  486. def same_scope(current):
  487. return current.scope() is node
  488. from_iter = itertools.chain.from_iterable
  489. nonlocals = set(from_iter(
  490. child.names for child in node.nodes_of_class(astroid.Nonlocal)
  491. if same_scope(child)))
  492. global_vars = set(from_iter(
  493. child.names for child in node.nodes_of_class(astroid.Global)
  494. if same_scope(child)))
  495. for name in nonlocals.intersection(global_vars):
  496. self.add_message('nonlocal-and-global',
  497. args=(name, ), node=node)
  498. @utils.check_messages('return-outside-function')
  499. def visit_return(self, node):
  500. if not isinstance(node.frame(), astroid.FunctionDef):
  501. self.add_message('return-outside-function', node=node)
  502. @utils.check_messages('yield-outside-function')
  503. def visit_yield(self, node):
  504. self._check_yield_outside_func(node)
  505. @utils.check_messages('yield-outside-function')
  506. def visit_yieldfrom(self, node):
  507. self._check_yield_outside_func(node)
  508. @utils.check_messages('not-in-loop', 'continue-in-finally')
  509. def visit_continue(self, node):
  510. self._check_in_loop(node, 'continue')
  511. @utils.check_messages('not-in-loop')
  512. def visit_break(self, node):
  513. self._check_in_loop(node, 'break')
  514. @utils.check_messages('useless-else-on-loop')
  515. def visit_for(self, node):
  516. self._check_else_on_loop(node)
  517. @utils.check_messages('useless-else-on-loop')
  518. def visit_while(self, node):
  519. self._check_else_on_loop(node)
  520. @utils.check_messages('nonexistent-operator')
  521. def visit_unaryop(self, node):
  522. """check use of the non-existent ++ and -- operator operator"""
  523. if ((node.op in '+-') and
  524. isinstance(node.operand, astroid.UnaryOp) and
  525. (node.operand.op == node.op)):
  526. self.add_message('nonexistent-operator', node=node, args=node.op*2)
  527. def _check_nonlocal_without_binding(self, node, name):
  528. current_scope = node.scope()
  529. while True:
  530. if current_scope.parent is None:
  531. break
  532. if not isinstance(current_scope, (astroid.ClassDef, astroid.FunctionDef)):
  533. self.add_message('nonlocal-without-binding', args=(name, ),
  534. node=node)
  535. return
  536. if name not in current_scope.locals:
  537. current_scope = current_scope.parent.scope()
  538. continue
  539. # Okay, found it.
  540. return
  541. if not isinstance(current_scope, astroid.FunctionDef):
  542. self.add_message('nonlocal-without-binding', args=(name, ), node=node)
  543. @utils.check_messages('nonlocal-without-binding')
  544. def visit_nonlocal(self, node):
  545. for name in node.names:
  546. self._check_nonlocal_without_binding(node, name)
  547. @utils.check_messages('abstract-class-instantiated')
  548. def visit_call(self, node):
  549. """ Check instantiating abstract class with
  550. abc.ABCMeta as metaclass.
  551. """
  552. try:
  553. for inferred in node.func.infer():
  554. self._check_inferred_class_is_abstract(inferred, node)
  555. except astroid.InferenceError:
  556. return
  557. def _check_inferred_class_is_abstract(self, infered, node):
  558. if not isinstance(infered, astroid.ClassDef):
  559. return
  560. klass = utils.node_frame_class(node)
  561. if klass is infered:
  562. # Don't emit the warning if the class is instantiated
  563. # in its own body or if the call is not an instance
  564. # creation. If the class is instantiated into its own
  565. # body, we're expecting that it knows what it is doing.
  566. return
  567. # __init__ was called
  568. metaclass = infered.metaclass()
  569. abstract_methods = _has_abstract_methods(infered)
  570. if metaclass is None:
  571. # Python 3.4 has `abc.ABC`, which won't be detected
  572. # by ClassNode.metaclass()
  573. for ancestor in infered.ancestors():
  574. if ancestor.qname() == 'abc.ABC' and abstract_methods:
  575. self.add_message('abstract-class-instantiated',
  576. args=(infered.name, ),
  577. node=node)
  578. break
  579. return
  580. if metaclass.qname() == 'abc.ABCMeta' and abstract_methods:
  581. self.add_message('abstract-class-instantiated',
  582. args=(infered.name, ),
  583. node=node)
  584. def _check_yield_outside_func(self, node):
  585. if not isinstance(node.frame(), (astroid.FunctionDef, astroid.Lambda)):
  586. self.add_message('yield-outside-function', node=node)
  587. def _check_else_on_loop(self, node):
  588. """Check that any loop with an else clause has a break statement."""
  589. if node.orelse and not _loop_exits_early(node):
  590. self.add_message('useless-else-on-loop', node=node,
  591. # This is not optimal, but the line previous
  592. # to the first statement in the else clause
  593. # will usually be the one that contains the else:.
  594. line=node.orelse[0].lineno - 1)
  595. def _check_in_loop(self, node, node_name):
  596. """check that a node is inside a for or while loop"""
  597. _node = node.parent
  598. while _node:
  599. if isinstance(_node, (astroid.For, astroid.While)):
  600. if node not in _node.orelse:
  601. return
  602. if isinstance(_node, (astroid.ClassDef, astroid.FunctionDef)):
  603. break
  604. if (isinstance(_node, astroid.TryFinally)
  605. and node in _node.finalbody
  606. and isinstance(node, astroid.Continue)):
  607. self.add_message('continue-in-finally', node=node)
  608. _node = _node.parent
  609. self.add_message('not-in-loop', node=node, args=node_name)
  610. def _check_redefinition(self, redeftype, node):
  611. """check for redefinition of a function / method / class name"""
  612. defined_self = node.parent.frame()[node.name]
  613. if defined_self is not node and not astroid.are_exclusive(node, defined_self):
  614. dummy_variables_rgx = lint_utils.get_global_option(
  615. self, 'dummy-variables-rgx', default=None)
  616. if dummy_variables_rgx and dummy_variables_rgx.match(node.name):
  617. return
  618. self.add_message('function-redefined', node=node,
  619. args=(redeftype, defined_self.fromlineno))
  620. class BasicChecker(_BasicChecker):
  621. """checks for :
  622. * doc strings
  623. * number of arguments, local variables, branches, returns and statements in
  624. functions, methods
  625. * required module attributes
  626. * dangerous default values as arguments
  627. * redefinition of function / method / class
  628. * uses of the global statement
  629. """
  630. __implements__ = interfaces.IAstroidChecker
  631. name = 'basic'
  632. msgs = {
  633. 'W0101': ('Unreachable code',
  634. 'unreachable',
  635. 'Used when there is some code behind a "return" or "raise" '
  636. 'statement, which will never be accessed.'),
  637. 'W0102': ('Dangerous default value %s as argument',
  638. 'dangerous-default-value',
  639. 'Used when a mutable value as list or dictionary is detected in '
  640. 'a default value for an argument.'),
  641. 'W0104': ('Statement seems to have no effect',
  642. 'pointless-statement',
  643. 'Used when a statement doesn\'t have (or at least seems to) '
  644. 'any effect.'),
  645. 'W0105': ('String statement has no effect',
  646. 'pointless-string-statement',
  647. 'Used when a string is used as a statement (which of course '
  648. 'has no effect). This is a particular case of W0104 with its '
  649. 'own message so you can easily disable it if you\'re using '
  650. 'those strings as documentation, instead of comments.'),
  651. 'W0106': ('Expression "%s" is assigned to nothing',
  652. 'expression-not-assigned',
  653. 'Used when an expression that is not a function call is assigned '
  654. 'to nothing. Probably something else was intended.'),
  655. 'W0108': ('Lambda may not be necessary',
  656. 'unnecessary-lambda',
  657. 'Used when the body of a lambda expression is a function call '
  658. 'on the same argument list as the lambda itself; such lambda '
  659. 'expressions are in all but a few cases replaceable with the '
  660. 'function being called in the body of the lambda.'),
  661. 'W0109': ("Duplicate key %r in dictionary",
  662. 'duplicate-key',
  663. 'Used when a dictionary expression binds the same key multiple '
  664. 'times.'),
  665. 'W0122': ('Use of exec',
  666. 'exec-used',
  667. 'Used when you use the "exec" statement (function for Python '
  668. '3), to discourage its usage. That doesn\'t '
  669. 'mean you cannot use it !'),
  670. 'W0123': ('Use of eval',
  671. 'eval-used',
  672. 'Used when you use the "eval" function, to discourage its '
  673. 'usage. Consider using `ast.literal_eval` for safely evaluating '
  674. 'strings containing Python expressions '
  675. 'from untrusted sources. '),
  676. 'W0150': ("%s statement in finally block may swallow exception",
  677. 'lost-exception',
  678. 'Used when a break or a return statement is found inside the '
  679. 'finally clause of a try...finally block: the exceptions raised '
  680. 'in the try clause will be silently swallowed instead of being '
  681. 're-raised.'),
  682. 'W0199': ('Assert called on a 2-uple. Did you mean \'assert x,y\'?',
  683. 'assert-on-tuple',
  684. 'A call of assert on a tuple will always evaluate to true if '
  685. 'the tuple is not empty, and will always evaluate to false if '
  686. 'it is.'),
  687. 'W0124': ('Following "as" with another context manager looks like a tuple.',
  688. 'confusing-with-statement',
  689. 'Emitted when a `with` statement component returns multiple values '
  690. 'and uses name binding with `as` only for a part of those values, '
  691. 'as in with ctx() as a, b. This can be misleading, since it\'s not '
  692. 'clear if the context manager returns a tuple or if the node without '
  693. 'a name binding is another context manager.'),
  694. 'W0125': ('Using a conditional statement with a constant value',
  695. 'using-constant-test',
  696. 'Emitted when a conditional statement (If or ternary if) '
  697. 'uses a constant value for its test. This might not be what '
  698. 'the user intended to do.'),
  699. 'E0111': ('The first reversed() argument is not a sequence',
  700. 'bad-reversed-sequence',
  701. 'Used when the first argument to reversed() builtin '
  702. 'isn\'t a sequence (does not implement __reversed__, '
  703. 'nor __getitem__ and __len__'),
  704. }
  705. reports = (('RP0101', 'Statistics by type', report_by_type_stats),)
  706. def __init__(self, linter):
  707. _BasicChecker.__init__(self, linter)
  708. self.stats = None
  709. self._tryfinallys = None
  710. def open(self):
  711. """initialize visit variables and statistics
  712. """
  713. self._tryfinallys = []
  714. self.stats = self.linter.add_stats(module=0, function=0,
  715. method=0, class_=0)
  716. @utils.check_messages('using-constant-test')
  717. def visit_if(self, node):
  718. self._check_using_constant_test(node, node.test)
  719. @utils.check_messages('using-constant-test')
  720. def visit_ifexp(self, node):
  721. self._check_using_constant_test(node, node.test)
  722. @utils.check_messages('using-constant-test')
  723. def visit_comprehension(self, node):
  724. if node.ifs:
  725. for if_test in node.ifs:
  726. self._check_using_constant_test(node, if_test)
  727. def _check_using_constant_test(self, node, test):
  728. const_nodes = (
  729. astroid.Module,
  730. astroid.scoped_nodes.GeneratorExp,
  731. astroid.Lambda, astroid.FunctionDef, astroid.ClassDef,
  732. astroid.bases.Generator, astroid.UnboundMethod,
  733. astroid.BoundMethod, astroid.Module)
  734. structs = (astroid.Dict, astroid.Tuple, astroid.Set)
  735. # These nodes are excepted, since they are not constant
  736. # values, requiring a computation to happen. The only type
  737. # of node in this list which doesn't have this property is
  738. # Attribute, which is excepted because the conditional statement
  739. # can be used to verify that the attribute was set inside a class,
  740. # which is definitely a valid use case.
  741. except_nodes = (astroid.Attribute, astroid.Call,
  742. astroid.BinOp, astroid.BoolOp, astroid.UnaryOp,
  743. astroid.Subscript)
  744. inferred = None
  745. emit = isinstance(test, (astroid.Const, ) + structs + const_nodes)
  746. if not isinstance(test, except_nodes):
  747. inferred = utils.safe_infer(test)
  748. if emit or isinstance(inferred, const_nodes):
  749. self.add_message('using-constant-test', node=node)
  750. def visit_module(self, _):
  751. """check module name, docstring and required arguments
  752. """
  753. self.stats['module'] += 1
  754. def visit_classdef(self, node): # pylint: disable=unused-argument
  755. """check module name, docstring and redefinition
  756. increment branch counter
  757. """
  758. self.stats['class'] += 1
  759. @utils.check_messages('pointless-statement', 'pointless-string-statement',
  760. 'expression-not-assigned')
  761. def visit_expr(self, node):
  762. """check for various kind of statements without effect"""
  763. expr = node.value
  764. if isinstance(expr, astroid.Const) and isinstance(expr.value,
  765. six.string_types):
  766. # treat string statement in a separated message
  767. # Handle PEP-257 attribute docstrings.
  768. # An attribute docstring is defined as being a string right after
  769. # an assignment at the module level, class level or __init__ level.
  770. scope = expr.scope()
  771. if isinstance(scope, (astroid.ClassDef, astroid.Module, astroid.FunctionDef)):
  772. if isinstance(scope, astroid.FunctionDef) and scope.name != '__init__':
  773. pass
  774. else:
  775. sibling = expr.previous_sibling()
  776. if (sibling is not None and sibling.scope() is scope and
  777. isinstance(sibling, astroid.Assign)):
  778. return
  779. self.add_message('pointless-string-statement', node=node)
  780. return
  781. # ignore if this is :
  782. # * a direct function call
  783. # * the unique child of a try/except body
  784. # * a yield (which are wrapped by a discard node in _ast XXX)
  785. # warn W0106 if we have any underlying function call (we can't predict
  786. # side effects), else pointless-statement
  787. if (isinstance(expr, (astroid.Yield, astroid.Await, astroid.Call)) or
  788. (isinstance(node.parent, astroid.TryExcept) and
  789. node.parent.body == [node])):
  790. return
  791. if any(expr.nodes_of_class(astroid.Call)):
  792. self.add_message('expression-not-assigned', node=node,
  793. args=expr.as_string())
  794. else:
  795. self.add_message('pointless-statement', node=node)
  796. @staticmethod
  797. def _filter_vararg(node, call_args):
  798. # Return the arguments for the given call which are
  799. # not passed as vararg.
  800. for arg in call_args:
  801. if isinstance(arg, astroid.Starred):
  802. if (isinstance(arg.value, astroid.Name)
  803. and arg.value.name != node.args.vararg):
  804. yield arg
  805. else:
  806. yield arg
  807. @staticmethod
  808. def _has_variadic_argument(args, variadic_name):
  809. if not args:
  810. return True
  811. for arg in args:
  812. if isinstance(arg.value, astroid.Name):
  813. if arg.value.name != variadic_name:
  814. return True
  815. else:
  816. return True
  817. return False
  818. @utils.check_messages('unnecessary-lambda')
  819. def visit_lambda(self, node):
  820. """check whether or not the lambda is suspicious
  821. """
  822. # if the body of the lambda is a call expression with the same
  823. # argument list as the lambda itself, then the lambda is
  824. # possibly unnecessary and at least suspicious.
  825. if node.args.defaults:
  826. # If the arguments of the lambda include defaults, then a
  827. # judgment cannot be made because there is no way to check
  828. # that the defaults defined by the lambda are the same as
  829. # the defaults defined by the function called in the body
  830. # of the lambda.
  831. return
  832. call = node.body
  833. if not isinstance(call, astroid.Call):
  834. # The body of the lambda must be a function call expression
  835. # for the lambda to be unnecessary.
  836. return
  837. if (isinstance(node.body.func, astroid.Attribute) and
  838. isinstance(node.body.func.expr, astroid.Call)):
  839. # Chained call, the intermediate call might
  840. # return something else (but we don't check that, yet).
  841. return
  842. ordinary_args = list(node.args.args)
  843. new_call_args = list(self._filter_vararg(node, call.args))
  844. if node.args.kwarg:
  845. if self._has_variadic_argument(call.kwargs, node.args.kwarg):
  846. return
  847. elif call.kwargs or call.keywords:
  848. return
  849. if node.args.vararg:
  850. if self._has_variadic_argument(call.starargs, node.args.vararg):
  851. return
  852. elif call.starargs:
  853. return
  854. # The "ordinary" arguments must be in a correspondence such that:
  855. # ordinary_args[i].name == call.args[i].name.
  856. if len(ordinary_args) != len(new_call_args):
  857. return
  858. for arg, passed_arg in zip(ordinary_args, new_call_args):
  859. if not isinstance(passed_arg, astroid.Name):
  860. return
  861. if arg.name != passed_arg.name:
  862. return
  863. self.add_message('unnecessary-lambda', line=node.fromlineno,
  864. node=node)
  865. @utils.check_messages('dangerous-default-value')
  866. def visit_functiondef(self, node):
  867. """check function name, docstring, arguments, redefinition,
  868. variable names, max locals
  869. """
  870. self.stats[node.is_method() and 'method' or 'function'] += 1
  871. self._check_dangerous_default(node)
  872. visit_asyncfunctiondef = visit_functiondef
  873. def _check_dangerous_default(self, node):
  874. # check for dangerous default values as arguments
  875. is_iterable = lambda n: isinstance(n, (astroid.List,
  876. astroid.Set,
  877. astroid.Dict))
  878. for default in node.args.defaults:
  879. try:
  880. value = next(default.infer())
  881. except astroid.InferenceError:
  882. continue
  883. if (isinstance(value, astroid.Instance) and
  884. value.qname() in DEFAULT_ARGUMENT_SYMBOLS):
  885. if value is default:
  886. msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()]
  887. elif isinstance(value, astroid.Instance) or is_iterable(value):
  888. # We are here in the following situation(s):
  889. # * a dict/set/list/tuple call which wasn't inferred
  890. # to a syntax node ({}, () etc.). This can happen
  891. # when the arguments are invalid or unknown to
  892. # the inference.
  893. # * a variable from somewhere else, which turns out to be a list
  894. # or a dict.
  895. if is_iterable(default):
  896. msg = value.pytype()
  897. elif isinstance(default, astroid.Call):
  898. msg = '%s() (%s)' % (value.name, value.qname())
  899. else:
  900. msg = '%s (%s)' % (default.as_string(), value.qname())
  901. else:
  902. # this argument is a name
  903. msg = '%s (%s)' % (default.as_string(),
  904. DEFAULT_ARGUMENT_SYMBOLS[value.qname()])
  905. self.add_message('dangerous-default-value',
  906. node=node,
  907. args=(msg, ))
  908. @utils.check_messages('unreachable', 'lost-exception')
  909. def visit_return(self, node):
  910. """1 - check is the node has a right sibling (if so, that's some
  911. unreachable code)
  912. 2 - check is the node is inside the finally clause of a try...finally
  913. block
  914. """
  915. self._check_unreachable(node)
  916. # Is it inside final body of a try...finally bloc ?
  917. self._check_not_in_finally(node, 'return', (astroid.FunctionDef,))
  918. @utils.check_messages('unreachable')
  919. def visit_continue(self, node):
  920. """check is the node has a right sibling (if so, that's some unreachable
  921. code)
  922. """
  923. self._check_unreachable(node)
  924. @utils.check_messages('unreachable', 'lost-exception')
  925. def visit_break(self, node):
  926. """1 - check is the node has a right sibling (if so, that's some
  927. unreachable code)
  928. 2 - check is the node is inside the finally clause of a try...finally
  929. block
  930. """
  931. # 1 - Is it right sibling ?
  932. self._check_unreachable(node)
  933. # 2 - Is it inside final body of a try...finally bloc ?
  934. self._check_not_in_finally(node, 'break', (astroid.For, astroid.While,))
  935. @utils.check_messages('unreachable')
  936. def visit_raise(self, node):
  937. """check if the node has a right sibling (if so, that's some unreachable
  938. code)
  939. """
  940. self._check_unreachable(node)
  941. @utils.check_messages('exec-used')
  942. def visit_exec(self, node):
  943. """just print a warning on exec statements"""
  944. self.add_message('exec-used', node=node)
  945. @utils.check_messages('eval-used', 'exec-used', 'bad-reversed-sequence')
  946. def visit_call(self, node):
  947. """visit a Call node -> check if this is not a blacklisted builtin
  948. call and check for * or ** use
  949. """
  950. if isinstance(node.func, astroid.Name):
  951. name = node.func.name
  952. # ignore the name if it's not a builtin (i.e. not defined in the
  953. # locals nor globals scope)
  954. if not (name in node.frame() or
  955. name in node.root()):
  956. if name == 'exec':
  957. self.add_message('exec-used', node=node)
  958. elif name == 'reversed':
  959. self._check_reversed(node)
  960. elif name == 'eval':
  961. self.add_message('eval-used', node=node)
  962. @utils.check_messages('assert-on-tuple')
  963. def visit_assert(self, node):
  964. """check the use of an assert statement on a tuple."""
  965. if node.fail is None and isinstance(node.test, astroid.Tuple) and \
  966. len(node.test.elts) == 2:
  967. self.add_message('assert-on-tuple', node=node)
  968. @utils.check_messages('duplicate-key')
  969. def visit_dict(self, node):
  970. """check duplicate key in dictionary"""
  971. keys = set()
  972. for k, _ in node.items:
  973. if isinstance(k, astroid.Const):
  974. key = k.value
  975. if key in keys:
  976. self.add_message('duplicate-key', node=node, args=key)
  977. keys.add(key)
  978. def visit_tryfinally(self, node):
  979. """update try...finally flag"""
  980. self._tryfinallys.append(node)
  981. def leave_tryfinally(self, node): # pylint: disable=unused-argument
  982. """update try...finally flag"""
  983. self._tryfinallys.pop()
  984. def _check_unreachable(self, node):
  985. """check unreachable code"""
  986. unreach_stmt = node.next_sibling()
  987. if unreach_stmt is not None:
  988. self.add_message('unreachable', node=unreach_stmt)
  989. def _check_not_in_finally(self, node, node_name, breaker_classes=()):
  990. """check that a node is not inside a finally clause of a
  991. try...finally statement.
  992. If we found before a try...finally bloc a parent which its type is
  993. in breaker_classes, we skip the whole check."""
  994. # if self._tryfinallys is empty, we're not a in try...finally bloc
  995. if not self._tryfinallys:
  996. return
  997. # the node could be a grand-grand...-children of the try...finally
  998. _parent = node.parent
  999. _node = node
  1000. while _parent and not isinstance(_parent, breaker_classes):
  1001. if hasattr(_parent, 'finalbody') and _node in _parent.finalbody:
  1002. self.add_message('lost-exception', node=node, args=node_name)
  1003. return
  1004. _node = _parent
  1005. _parent = _node.parent
  1006. def _check_reversed(self, node):
  1007. """ check that the argument to `reversed` is a sequence """
  1008. try:
  1009. argument = utils.safe_infer(utils.get_argument_from_call(node, position=0))
  1010. except utils.NoSuchArgumentError:
  1011. pass
  1012. else:
  1013. if argument is astroid.YES:
  1014. return
  1015. if argument is None:
  1016. # Nothing was infered.
  1017. # Try to see if we have iter().
  1018. if isinstance(node.args[0], astroid.Call):
  1019. try:
  1020. func = next(node.args[0].func.infer())
  1021. except astroid.InferenceError:
  1022. return
  1023. if (getattr(func, 'name', None) == 'iter' and
  1024. utils.is_builtin_object(func)):
  1025. self.add_message('bad-reversed-sequence', node=node)
  1026. return
  1027. if isinstance(argument, astroid.Instance):
  1028. if (argument._proxied.name == 'dict' and
  1029. utils.is_builtin_object(argument._proxied)):
  1030. self.add_message('bad-reversed-sequence', node=node)
  1031. return
  1032. elif any(ancestor.name == 'dict' and utils.is_builtin_object(ancestor)
  1033. for ancestor in argument._proxied.ancestors()):
  1034. # Mappings aren't accepted by reversed(), unless
  1035. # they provide explicitly a __reversed__ method.
  1036. try:
  1037. argument.locals[REVERSED_PROTOCOL_METHOD]
  1038. except KeyError:
  1039. self.add_message('bad-reversed-sequence', node=node)
  1040. return
  1041. for methods in REVERSED_METHODS:
  1042. for meth in methods:
  1043. try:
  1044. argument.getattr(meth)
  1045. except astroid.NotFoundError:
  1046. break
  1047. else:
  1048. break
  1049. else:
  1050. self.add_message('bad-reversed-sequence', node=node)
  1051. elif not isinstance(argument, (astroid.List, astroid.Tuple)):
  1052. # everything else is not a proper sequence for reversed()
  1053. self.add_message('bad-reversed-sequence', node=node)
  1054. @utils.check_messages('confusing-with-statement')
  1055. def visit_with(self, node):
  1056. if not PY3K:
  1057. # in Python 2 a "with" statement with multiple managers coresponds
  1058. # to multiple nested AST "With" nodes
  1059. pairs = []
  1060. parent_node = node.parent
  1061. if isinstance(parent_node, astroid.With):
  1062. # we only care about the direct parent, since this method
  1063. # gets called for each with node anyway
  1064. pairs.extend(parent_node.items)
  1065. pairs.extend(node.items)
  1066. else:
  1067. # in PY3K a "with" statement with multiple managers coresponds
  1068. # to one AST "With" node with multiple items
  1069. pairs = node.items
  1070. if pairs:
  1071. for prev_pair, pair in zip(pairs, pairs[1:]):
  1072. if (isinstance(prev_pair[1], astroid.AssignName) and
  1073. (pair[1] is None and not isinstance(pair[0], astroid.Call))):
  1074. # don't emit a message if the second is a function call
  1075. # there's no way that can be mistaken for a name assignment
  1076. if PY3K or node.lineno == node.parent.lineno:
  1077. # if the line number doesn't match
  1078. # we assume it's a nested "with"
  1079. self.add_message('confusing-with-statement', node=node)
  1080. KNOWN_NAME_TYPES = {
  1081. "module", "const", "class", "function", "method", "attr",
  1082. "argument", "variable", "class_attribute", "inlinevar"
  1083. }
  1084. HUMAN_READABLE_TYPES = {
  1085. 'module': 'module',
  1086. 'const': 'constant',
  1087. 'class': 'class',
  1088. 'function': 'function',
  1089. 'method': 'method',
  1090. 'attr': 'attribute',
  1091. 'argument': 'argument',
  1092. 'variable': 'variable',
  1093. 'class_attribute': 'class attribute',
  1094. 'inlinevar': 'inline iteration',
  1095. }
  1096. DEFAULT_NAMING_STYLES = {
  1097. "module": "snake_case",
  1098. "const": "UPPER_CASE",
  1099. "class": "PascalCase",
  1100. "function": "snake_case",
  1101. "method": "snake_case",
  1102. "attr": "snake_case",
  1103. "argument": "snake_case",
  1104. "variable": "snake_case",
  1105. "class_attribute": "any",
  1106. "inlinevar": "any",
  1107. }
  1108. def _create_naming_options():
  1109. name_options = []
  1110. for name_type in KNOWN_NAME_TYPES:
  1111. human_readable_name = HUMAN_READABLE_TYPES[name_type]
  1112. default_style = DEFAULT_NAMING_STYLES[name_type]
  1113. name_type = name_type.replace('_', '-')
  1114. name_options.append((
  1115. '%s-naming-style' % (name_type,),
  1116. {'default': default_style,
  1117. 'type': 'choice', 'choices': list(NAMING_STYLES.keys()), 'metavar': '<style>',
  1118. 'help': 'Naming style matching correct %s names' % (human_readable_name,)}),)
  1119. name_options.append((
  1120. '%s-rgx' % (name_type,),
  1121. {'default': None, 'type': 'regexp', 'metavar': '<regexp>',
  1122. 'help': 'Regular expression matching correct %s names. Overrides %s-naming-style'
  1123. % (human_readable_name, name_type,)}))
  1124. return tuple(name_options)
  1125. class NameChecker(_BasicChecker):
  1126. msgs = {
  1127. 'C0102': ('Black listed name "%s"',
  1128. 'blacklisted-name',
  1129. 'Used when the name is listed in the black list (unauthorized '
  1130. 'names).'),
  1131. 'C0103': ('%s name "%s" doesn\'t conform to %s',
  1132. 'invalid-name',
  1133. 'Used when the name doesn\'t conform to naming rules '
  1134. 'associated to its type (constant, variable, class...).'),
  1135. 'W0111': ('Name %s will become a keyword in Python %s',
  1136. 'assign-to-new-keyword',
  1137. 'Used when assignment will become invalid in future '
  1138. 'Python release due to introducing new keyword'),
  1139. }
  1140. options = (('good-names',
  1141. {'default' : ('i', 'j', 'k', 'ex', 'Run', '_'),
  1142. 'type' :'csv', 'metavar' : '<names>',
  1143. 'help' : 'Good variable names which should always be accepted,'
  1144. ' separated by a comma'}
  1145. ),
  1146. ('bad-names',
  1147. {'default' : ('foo', 'bar', 'baz', 'toto', 'tutu', 'tata'),
  1148. 'type' :'csv', 'metavar' : '<names>',
  1149. 'help' : 'Bad variable names which should always be refused, '
  1150. 'separated by a comma'}
  1151. ),
  1152. ('name-group',
  1153. {'default' : (),
  1154. 'type' :'csv', 'metavar' : '<name1:name2>',
  1155. 'help' : ('Colon-delimited sets of names that determine each'
  1156. ' other\'s naming style when the name regexes'
  1157. ' allow several styles.')}
  1158. ),
  1159. ('include-naming-hint',
  1160. {'default': False, 'type': 'yn', 'metavar': '<y_or_n>',
  1161. 'help': 'Include a hint for the correct naming format with invalid-name'}
  1162. ),
  1163. ('property-classes',
  1164. {'default': ('abc.abstractproperty',),
  1165. 'type': 'csv',
  1166. 'metavar': '<decorator names>',
  1167. 'help': 'List of decorators that produce properties, such as '
  1168. 'abc.abstractproperty. Add to this list to register '
  1169. 'other decorators that produce valid properties.'}
  1170. ),
  1171. ) + _create_naming_options()
  1172. KEYWORD_ONSET = {
  1173. (3, 0): {'True', 'False'},
  1174. (3, 7): {'async', 'await'}
  1175. }
  1176. def __init__(self, linter):
  1177. _BasicChecker.__init__(self, linter)
  1178. self._name_category = {}
  1179. self._name_group = {}
  1180. self._bad_names = {}
  1181. self._name_regexps = {}
  1182. self._name_hints = {}
  1183. def open(self):
  1184. self.stats = self.linter.add_stats(badname_module=0,
  1185. badname_class=0, badname_function=0,
  1186. badname_method=0, badname_attr=0,
  1187. badname_const=0,
  1188. badname_variable=0,
  1189. badname_inlinevar=0,
  1190. badname_argument=0,
  1191. badname_class_attribute=0)
  1192. for group in self.config.name_group:
  1193. for name_type in group.split(':'):
  1194. self._name_group[name_type] = 'group_%s' % (group,)
  1195. regexps, hints = self._create_naming_rules()
  1196. self._name_regexps = regexps
  1197. self._name_hints = hints
  1198. def _create_naming_rules(self):
  1199. regexps = {}
  1200. hints = {}
  1201. for name_type in KNOWN_NAME_TYPES:
  1202. naming_style_option_name = "%s_naming_style" % (name_type,)
  1203. naming_style_name = getattr(self.config, naming_style_option_name)
  1204. regexps[name_type] = NAMING_STYLES[naming_style_name].get_regex(name_type)
  1205. custom_regex_setting_name = "%s_rgx" % (name_type, )
  1206. custom_regex = getattr(self.config, custom_regex_setting_name, None)
  1207. if custom_regex is not None:
  1208. regexps[name_type] = custom_regex
  1209. if custom_regex is not None:
  1210. hints[name_type] = "%r pattern" % custom_regex.pattern
  1211. else:
  1212. hints[name_type] = "%s naming style" % naming_style_name
  1213. return regexps, hints
  1214. @utils.check_messages('blacklisted-name', 'invalid-name')
  1215. def visit_module(self, node):
  1216. self._check_name('module', node.name.split('.')[-1], node)
  1217. self._bad_names = {}
  1218. def leave_module(self, node): # pylint: disable=unused-argument
  1219. for all_groups in six.itervalues(self._bad_names):
  1220. if len(all_groups) < 2:
  1221. continue
  1222. groups = collections.defaultdict(list)
  1223. min_warnings = sys.maxsize
  1224. for group in six.itervalues(all_groups):
  1225. groups[len(group)].append(group)
  1226. min_warnings = min(len(group), min_warnings)
  1227. if len(groups[min_warnings]) > 1:
  1228. by_line = sorted(groups[min_warnings],
  1229. key=lambda group: min(warning[0].lineno for warning in group))
  1230. warnings = itertools.chain(*by_line[1:])
  1231. else:
  1232. warnings = groups[min_warnings][0]
  1233. for args in warnings:
  1234. self._raise_name_warning(*args)
  1235. @utils.check_messages('blacklisted-name', 'invalid-name', 'assign-to-new-keyword')
  1236. def visit_classdef(self, node):
  1237. self._check_assign_to_new_keyword_violation(node.name, node)
  1238. self._check_name('class', node.name, node)
  1239. for attr, anodes in six.iteritems(node.instance_attrs):
  1240. if not any(node.instance_attr_ancestors(attr)):
  1241. self._check_name('attr', attr, anodes[0])
  1242. @utils.check_messages('blacklisted-name', 'invalid-name', 'assign-to-new-keyword')
  1243. def visit_functiondef(self, node):
  1244. # Do not emit any warnings if the method is just an implementation
  1245. # of a base class method.
  1246. self._check_assign_to_new_keyword_violation(node.name, node)
  1247. confidence = interfaces.HIGH
  1248. if node.is_method():
  1249. if utils.overrides_a_method(node.parent.frame(), node.name):
  1250. return
  1251. confidence = (interfaces.INFERENCE if utils.has_known_bases(node.parent.frame())
  1252. else interfaces.INFERENCE_FAILURE)
  1253. self._check_name(_determine_function_name_type(node,
  1254. config=self.config),
  1255. node.name, node, confidence)
  1256. # Check argument names
  1257. args = node.args.args
  1258. if args is not None:
  1259. self._recursive_check_names(args, node)
  1260. visit_asyncfunctiondef = visit_functiondef
  1261. @utils.check_messages('blacklisted-name', 'invalid-name')
  1262. def visit_global(self, node):
  1263. for name in node.names:
  1264. self._check_name('const', name, node)
  1265. @utils.check_messages('blacklisted-name', 'invalid-name', 'assign-to-new-keyword')
  1266. def visit_assignname(self, node):
  1267. """check module level assigned names"""
  1268. self._check_assign_to_new_keyword_violation(node.name, node)
  1269. frame = node.frame()
  1270. ass_type = node.assign_type()
  1271. if isinstance(ass_type, astroid.Comprehension):
  1272. self._check_name('inlinevar', node.name, node)
  1273. elif isinstance(frame, astroid.Module):
  1274. if isinstance(ass_type, astroid.Assign) and not in_loop(ass_type):
  1275. if isinstance(utils.safe_infer(ass_type.value), astroid.ClassDef):
  1276. self._check_name('class', node.name, node)
  1277. else:
  1278. if not _redefines_import(node):
  1279. # Don't emit if the name redefines an import
  1280. # in an ImportError except handler.
  1281. self._check_name('const', node.name, node)
  1282. elif isinstance(ass_type, astroid.ExceptHandler):
  1283. self._check_name('variable', node.name, node)
  1284. elif isinstance(frame, astroid.FunctionDef):
  1285. # global introduced variable aren't in the function locals
  1286. if node.name in frame and node.name not in frame.argnames():
  1287. if not _redefines_import(node):
  1288. self._check_name('variable', node.name, node)
  1289. elif isinstance(frame, astroid.ClassDef):
  1290. if not list(frame.local_attr_ancestors(node.name)):
  1291. self._check_name('class_attribute', node.name, node)
  1292. def _recursive_check_names(self, args, node):
  1293. """check names in a possibly recursive list <arg>"""
  1294. for arg in args:
  1295. if isinstance(arg, astroid.AssignName):
  1296. self._check_name('argument', arg.name, node)
  1297. else:
  1298. self._recursive_check_names(arg.elts, node)
  1299. def _find_name_group(self, node_type):
  1300. return self._name_group.get(node_type, node_type)
  1301. def _raise_name_warning(self, node, node_type, name, confidence):
  1302. type_label = HUMAN_READABLE_TYPES[node_type]
  1303. hint = self._name_hints[node_type]
  1304. if self.config.include_naming_hint:
  1305. hint += " (%r pattern)" % self._name_regexps[node_type].pattern
  1306. args = (
  1307. type_label.capitalize(),
  1308. name,
  1309. hint
  1310. )
  1311. self.add_message('invalid-name', node=node, args=args,
  1312. confidence=confidence)
  1313. self.stats['badname_' + node_type] += 1
  1314. def _check_name(self, node_type, name, node, confidence=interfaces.HIGH):
  1315. """check for a name using the type's regexp"""
  1316. if utils.is_inside_except(node):
  1317. clobbering, _ = utils.clobber_in_except(node)
  1318. if clobbering:
  1319. return
  1320. if name in self.config.good_names:
  1321. return
  1322. if name in self.config.bad_names:
  1323. self.stats['badname_' + node_type] += 1
  1324. self.add_message('blacklisted-name', node=node, args=name)
  1325. return
  1326. regexp = self._name_regexps[node_type]
  1327. match = regexp.match(name)
  1328. if _is_multi_naming_match(match, node_type, confidence):
  1329. name_group = self._find_name_group(node_type)
  1330. bad_name_group = self._bad_names.setdefault(name_group, {})
  1331. warnings = bad_name_group.setdefault(match.lastgroup, [])
  1332. warnings.append((node, node_type, name, confidence))
  1333. if match is None:
  1334. self._raise_name_warning(node, node_type, name, confidence)
  1335. def _check_assign_to_new_keyword_violation(self, name, node):
  1336. keyword_first_version = self._name_became_keyword_in_version(
  1337. name, self.KEYWORD_ONSET
  1338. )
  1339. if keyword_first_version is not None:
  1340. self.add_message('assign-to-new-keyword',
  1341. node=node, args=(name, keyword_first_version),
  1342. confidence=interfaces.HIGH)
  1343. @staticmethod
  1344. def _name_became_keyword_in_version(name, rules):
  1345. for version, keywords in rules.items():
  1346. if name in keywords and sys.version_info < version:
  1347. return '.'.join(map(str, version))
  1348. return None
  1349. class DocStringChecker(_BasicChecker):
  1350. msgs = {
  1351. 'C0111': ('Missing %s docstring', # W0131
  1352. 'missing-docstring',
  1353. 'Used when a module, function, class or method has no docstring.'
  1354. 'Some special methods like __init__ doesn\'t necessary require a '
  1355. 'docstring.'),
  1356. 'C0112': ('Empty %s docstring', # W0132
  1357. 'empty-docstring',
  1358. 'Used when a module, function, class or method has an empty '
  1359. 'docstring (it would be too easy ;).'),
  1360. }
  1361. options = (('no-docstring-rgx',
  1362. {'default' : NO_REQUIRED_DOC_RGX,
  1363. 'type' : 'regexp', 'metavar' : '<regexp>',
  1364. 'help' : 'Regular expression which should only match '
  1365. 'function or class names that do not require a '
  1366. 'docstring.'}
  1367. ),
  1368. ('docstring-min-length',
  1369. {'default' : -1,
  1370. 'type' : 'int', 'metavar' : '<int>',
  1371. 'help': ('Minimum line length for functions/classes that'
  1372. ' require docstrings, shorter ones are exempt.')}
  1373. ),
  1374. )
  1375. def open(self):
  1376. self.stats = self.linter.add_stats(undocumented_module=0,
  1377. undocumented_function=0,
  1378. undocumented_method=0,
  1379. undocumented_class=0)
  1380. @utils.check_messages('missing-docstring', 'empty-docstring')
  1381. def visit_module(self, node):
  1382. self._check_docstring('module', node)
  1383. @utils.check_messages('missing-docstring', 'empty-docstring')
  1384. def visit_classdef(self, node):
  1385. if self.config.no_docstring_rgx.match(node.name) is None:
  1386. self._check_docstring('class', node)
  1387. @staticmethod
  1388. def _is_setter_or_deleter(node):
  1389. names = {'setter', 'deleter'}
  1390. for decorator in node.decorators.nodes:
  1391. if (isinstance(decorator, astroid.Attribute)
  1392. and decorator.attrname in names):
  1393. return True
  1394. return False
  1395. @utils.check_messages('missing-docstring', 'empty-docstring')
  1396. def visit_functiondef(self, node):
  1397. if self.config.no_docstring_rgx.match(node.name) is None:
  1398. ftype = 'method' if node.is_method() else 'function'
  1399. if node.decorators and self._is_setter_or_deleter(node):
  1400. return
  1401. if isinstance(node.parent.frame(), astroid.ClassDef):
  1402. overridden = False
  1403. confidence = (interfaces.INFERENCE if utils.has_known_bases(node.parent.frame())
  1404. else interfaces.INFERENCE_FAILURE)
  1405. # check if node is from a method overridden by its ancestor
  1406. for ancestor in node.parent.frame().ancestors():
  1407. if node.name in ancestor and \
  1408. isinstance(ancestor[node.name], astroid.FunctionDef):
  1409. overridden = True
  1410. break
  1411. self._check_docstring(ftype, node,
  1412. report_missing=not overridden,
  1413. confidence=confidence)
  1414. else:
  1415. self._check_docstring(ftype, node)
  1416. visit_asyncfunctiondef = visit_functiondef
  1417. def _check_docstring(self, node_type, node, report_missing=True,
  1418. confidence=interfaces.HIGH):
  1419. """check the node has a non empty docstring"""
  1420. docstring = node.doc
  1421. if docstring is None:
  1422. if not report_missing:
  1423. return
  1424. lines = get_node_last_lineno(node) - node.lineno
  1425. if node_type == 'module' and not lines:
  1426. # If the module has no body, there's no reason
  1427. # to require a docstring.
  1428. return
  1429. max_lines = self.config.docstring_min_length
  1430. if node_type != 'module' and max_lines > -1 and lines < max_lines:
  1431. return
  1432. self.stats['undocumented_'+node_type] += 1
  1433. if (node.body and isinstance(node.body[0], astroid.Expr) and
  1434. isinstance(node.body[0].value, astroid.Call)):
  1435. # Most likely a string with a format call. Let's see.
  1436. func = utils.safe_infer(node.body[0].value.func)
  1437. if (isinstance(func, astroid.BoundMethod)
  1438. and isinstance(func.bound, astroid.Instance)):
  1439. # Strings in Python 3, others in Python 2.
  1440. if PY3K and func.bound.name == 'str':
  1441. return
  1442. elif func.bound.name in ('str', 'unicode', 'bytes'):
  1443. return
  1444. self.add_message('missing-docstring', node=node, args=(node_type,),
  1445. confidence=confidence)
  1446. elif not docstring.strip():
  1447. self.stats['undocumented_'+node_type] += 1
  1448. self.add_message('empty-docstring', node=node, args=(node_type,),
  1449. confidence=confidence)
  1450. class PassChecker(_BasicChecker):
  1451. """check if the pass statement is really necessary"""
  1452. msgs = {'W0107': ('Unnecessary pass statement',
  1453. 'unnecessary-pass',
  1454. 'Used when a "pass" statement that can be avoided is '
  1455. 'encountered.'),
  1456. }
  1457. @utils.check_messages('unnecessary-pass')
  1458. def visit_pass(self, node):
  1459. if len(node.parent.child_sequence(node)) > 1:
  1460. self.add_message('unnecessary-pass', node=node)
  1461. class LambdaForComprehensionChecker(_BasicChecker):
  1462. """check for using a lambda where a comprehension would do.
  1463. See <http://www.artima.com/weblogs/viewpost.jsp?thread=98196>
  1464. where GvR says comprehensions would be clearer.
  1465. """
  1466. msgs = {'W0110': ('map/filter on lambda could be replaced by comprehension',
  1467. 'deprecated-lambda',
  1468. 'Used when a lambda is the first argument to "map" or '
  1469. '"filter". It could be clearer as a list '
  1470. 'comprehension or generator expression.',
  1471. {'maxversion': (3, 0)}),
  1472. }
  1473. @utils.check_messages('deprecated-lambda')
  1474. def visit_call(self, node):
  1475. """visit a Call node, check if map or filter are called with a
  1476. lambda
  1477. """
  1478. if not node.args:
  1479. return
  1480. if not isinstance(node.args[0], astroid.Lambda):
  1481. return
  1482. infered = utils.safe_infer(node.func)
  1483. if (utils.is_builtin_object(infered)
  1484. and infered.name in ['map', 'filter']):
  1485. self.add_message('deprecated-lambda', node=node)
  1486. def _is_one_arg_pos_call(call):
  1487. """Is this a call with exactly 1 argument,
  1488. where that argument is positional?
  1489. """
  1490. return (isinstance(call, astroid.Call)
  1491. and len(call.args) == 1 and not call.keywords)
  1492. class ComparisonChecker(_BasicChecker):
  1493. """Checks for comparisons
  1494. - singleton comparison: 'expr == True', 'expr == False' and 'expr == None'
  1495. - yoda condition: 'const "comp" right' where comp can be '==', '!=', '<',
  1496. '<=', '>' or '>=', and right can be a variable, an attribute, a method or
  1497. a function
  1498. """
  1499. msgs = {'C0121': ('Comparison to %s should be %s',
  1500. 'singleton-comparison',
  1501. 'Used when an expression is compared to singleton '
  1502. 'values like True, False or None.'),
  1503. 'C0122': ('Comparison should be %s',
  1504. 'misplaced-comparison-constant',
  1505. 'Used when the constant is placed on the left side '
  1506. 'of a comparison. It is usually clearer in intent to '
  1507. 'place it in the right hand side of the comparison.'),
  1508. 'C0123': ('Using type() instead of isinstance() for a typecheck.',
  1509. 'unidiomatic-typecheck',
  1510. 'The idiomatic way to perform an explicit typecheck in '
  1511. 'Python is to use isinstance(x, Y) rather than '
  1512. 'type(x) == Y, type(x) is Y. Though there are unusual '
  1513. 'situations where these give different results.',
  1514. {'old_names': [('W0154', 'unidiomatic-typecheck')]}),
  1515. 'R0123': ('Comparison to literal',
  1516. 'literal-comparison',
  1517. 'Used when comparing an object to a literal, which is usually '
  1518. 'what you do not want to do, since you can compare to a different '
  1519. 'literal than what was expected altogether.'),
  1520. }
  1521. def _check_singleton_comparison(self, singleton, root_node):
  1522. if singleton.value is True:
  1523. suggestion = "just 'expr' or 'expr is True'"
  1524. self.add_message('singleton-comparison',
  1525. node=root_node,
  1526. args=(True, suggestion))
  1527. elif singleton.value is False:
  1528. suggestion = "'not expr' or 'expr is False'"
  1529. self.add_message('singleton-comparison',
  1530. node=root_node,
  1531. args=(False, suggestion))
  1532. elif singleton.value is None:
  1533. self.add_message('singleton-comparison',
  1534. node=root_node,
  1535. args=(None, "'expr is None'"))
  1536. def _check_literal_comparison(self, literal, node):
  1537. """Check if we compare to a literal, which is usually what we do not want to do."""
  1538. nodes = (astroid.List,
  1539. astroid.Tuple,
  1540. astroid.Dict,
  1541. astroid.Set)
  1542. is_other_literal = isinstance(literal, nodes)
  1543. is_const = False
  1544. if isinstance(literal, astroid.Const):
  1545. if literal.value in (True, False, None):
  1546. # Not interested in this values.
  1547. return
  1548. is_const = isinstance(literal.value, (bytes, str, int, float))
  1549. if is_const or is_other_literal:
  1550. self.add_message('literal-comparison', node=node)
  1551. def _check_misplaced_constant(self, node, left, right, operator):
  1552. if isinstance(right, astroid.Const):
  1553. return
  1554. operator = REVERSED_COMPS.get(operator, operator)
  1555. suggestion = '%s %s %r' % (right.as_string(), operator, left.value)
  1556. self.add_message('misplaced-comparison-constant', node=node,
  1557. args=(suggestion,))
  1558. @utils.check_messages('singleton-comparison', 'misplaced-comparison-constant',
  1559. 'unidiomatic-typecheck', 'literal-comparison')
  1560. def visit_compare(self, node):
  1561. self._check_unidiomatic_typecheck(node)
  1562. # NOTE: this checker only works with binary comparisons like 'x == 42'
  1563. # but not 'x == y == 42'
  1564. if len(node.ops) != 1:
  1565. return
  1566. left = node.left
  1567. operator, right = node.ops[0]
  1568. if (operator in ('<', '<=', '>', '>=', '!=', '==')
  1569. and isinstance(left, astroid.Const)):
  1570. self._check_misplaced_constant(node, left, right, operator)
  1571. if operator == '==':
  1572. if isinstance(left, astroid.Const):
  1573. self._check_singleton_comparison(left, node)
  1574. elif isinstance(right, astroid.Const):
  1575. self._check_singleton_comparison(right, node)
  1576. if operator in ('is', 'is not'):
  1577. self._check_literal_comparison(right, node)
  1578. def _check_unidiomatic_typecheck(self, node):
  1579. operator, right = node.ops[0]
  1580. if operator in TYPECHECK_COMPARISON_OPERATORS:
  1581. left = node.left
  1582. if _is_one_arg_pos_call(left):
  1583. self._check_type_x_is_y(node, left, operator, right)
  1584. def _check_type_x_is_y(self, node, left, operator, right):
  1585. """Check for expressions like type(x) == Y."""
  1586. left_func = utils.safe_infer(left.func)
  1587. if not (isinstance(left_func, astroid.ClassDef)
  1588. and left_func.qname() == TYPE_QNAME):
  1589. return
  1590. if operator in ('is', 'is not') and _is_one_arg_pos_call(right):
  1591. right_func = utils.safe_infer(right.func)
  1592. if (isinstance(right_func, astroid.ClassDef)
  1593. and right_func.qname() == TYPE_QNAME):
  1594. # type(x) == type(a)
  1595. right_arg = utils.safe_infer(right.args[0])
  1596. if not isinstance(right_arg, LITERAL_NODE_TYPES):
  1597. # not e.g. type(x) == type([])
  1598. return
  1599. self.add_message('unidiomatic-typecheck', node=node)
  1600. def register(linter):
  1601. """required method to auto register this checker"""
  1602. linter.register_checker(BasicErrorChecker(linter))
  1603. linter.register_checker(BasicChecker(linter))
  1604. linter.register_checker(NameChecker(linter))
  1605. linter.register_checker(DocStringChecker(linter))
  1606. linter.register_checker(PassChecker(linter))
  1607. linter.register_checker(LambdaForComprehensionChecker(linter))
  1608. linter.register_checker(ComparisonChecker(linter))