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.

variables.py 60KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2009 Mads Kiilerich <mads@kiilerich.com>
  4. # Copyright (c) 2010 Daniel Harding <dharding@gmail.com>
  5. # Copyright (c) 2011-2014, 2017 Google, Inc.
  6. # Copyright (c) 2012 FELD Boris <lothiraldan@gmail.com>
  7. # Copyright (c) 2013-2018 Claudiu Popa <pcmanticore@gmail.com>
  8. # Copyright (c) 2014 Michal Nowikowski <godfryd@gmail.com>
  9. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  10. # Copyright (c) 2014 Ricardo Gemignani <ricardo.gemignani@gmail.com>
  11. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  12. # Copyright (c) 2015 Dmitry Pribysh <dmand@yandex.ru>
  13. # Copyright (c) 2015 Radu Ciorba <radu@devrandom.ro>
  14. # Copyright (c) 2015 Simu Toni <simutoni@gmail.com>
  15. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  16. # Copyright (c) 2016, 2018 Ashley Whetter <ashley@awhetter.co.uk>
  17. # Copyright (c) 2016-2017 Derek Gustafson <degustaf@gmail.com>
  18. # Copyright (c) 2016-2017 Łukasz Rogalski <rogalski.91@gmail.com>
  19. # Copyright (c) 2016 Grant Welch <gwelch925+github@gmail.com>
  20. # Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net>
  21. # Copyright (c) 2017-2018 hippo91 <guillaume.peillex@gmail.com>
  22. # Copyright (c) 2017 Dan Garrette <dhgarrette@gmail.com>
  23. # Copyright (c) 2017 Ville Skyttä <ville.skytta@iki.fi>
  24. # Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com>
  25. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  26. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  27. """variables checkers for Python code
  28. """
  29. import copy
  30. import itertools
  31. import collections
  32. import os
  33. import sys
  34. import re
  35. try:
  36. from functools import lru_cache
  37. except ImportError:
  38. from backports.functools_lru_cache import lru_cache
  39. import six
  40. import astroid
  41. from astroid import decorators
  42. from astroid import modutils
  43. from pylint.interfaces import IAstroidChecker, INFERENCE, INFERENCE_FAILURE, HIGH
  44. from pylint.utils import get_global_option
  45. from pylint.checkers import BaseChecker
  46. from pylint.checkers import utils
  47. SPECIAL_OBJ = re.compile("^_{2}[a-z]+_{2}$")
  48. FUTURE = '__future__'
  49. # regexp for ignored argument name
  50. IGNORED_ARGUMENT_NAMES = re.compile('_.*|^ignored_|^unused_')
  51. PY3K = sys.version_info >= (3, 0)
  52. def _is_from_future_import(stmt, name):
  53. """Check if the name is a future import from another module."""
  54. try:
  55. module = stmt.do_import_module(stmt.modname)
  56. except astroid.AstroidBuildingException:
  57. return None
  58. for local_node in module.locals.get(name, []):
  59. if (isinstance(local_node, astroid.ImportFrom)
  60. and local_node.modname == FUTURE):
  61. return True
  62. return None
  63. def in_for_else_branch(parent, stmt):
  64. """Returns True if stmt in inside the else branch for a parent For stmt."""
  65. return (isinstance(parent, astroid.For) and
  66. any(else_stmt.parent_of(stmt) or else_stmt == stmt
  67. for else_stmt in parent.orelse))
  68. @lru_cache(maxsize=1000)
  69. def overridden_method(klass, name):
  70. """get overridden method if any"""
  71. try:
  72. parent = next(klass.local_attr_ancestors(name))
  73. except (StopIteration, KeyError):
  74. return None
  75. try:
  76. meth_node = parent[name]
  77. except KeyError:
  78. # We have found an ancestor defining <name> but it's not in the local
  79. # dictionary. This may happen with astroid built from living objects.
  80. return None
  81. if isinstance(meth_node, astroid.FunctionDef):
  82. return meth_node
  83. return None
  84. def _get_unpacking_extra_info(node, infered):
  85. """return extra information to add to the message for unpacking-non-sequence
  86. and unbalanced-tuple-unpacking errors
  87. """
  88. more = ''
  89. infered_module = infered.root().name
  90. if node.root().name == infered_module:
  91. if node.lineno == infered.lineno:
  92. more = ' %s' % infered.as_string()
  93. elif infered.lineno:
  94. more = ' defined at line %s' % infered.lineno
  95. elif infered.lineno:
  96. more = ' defined at line %s of %s' % (infered.lineno, infered_module)
  97. return more
  98. def _detect_global_scope(node, frame, defframe):
  99. """ Detect that the given frames shares a global
  100. scope.
  101. Two frames shares a global scope when neither
  102. of them are hidden under a function scope, as well
  103. as any of parent scope of them, until the root scope.
  104. In this case, depending from something defined later on
  105. will not work, because it is still undefined.
  106. Example:
  107. class A:
  108. # B has the same global scope as `C`, leading to a NameError.
  109. class B(C): ...
  110. class C: ...
  111. """
  112. def_scope = scope = None
  113. if frame and frame.parent:
  114. scope = frame.parent.scope()
  115. if defframe and defframe.parent:
  116. def_scope = defframe.parent.scope()
  117. if isinstance(frame, astroid.FunctionDef):
  118. # If the parent of the current node is a
  119. # function, then it can be under its scope
  120. # (defined in, which doesn't concern us) or
  121. # the `->` part of annotations. The same goes
  122. # for annotations of function arguments, they'll have
  123. # their parent the Arguments node.
  124. if not isinstance(node.parent,
  125. (astroid.FunctionDef, astroid.Arguments)):
  126. return False
  127. elif any(not isinstance(f, (astroid.ClassDef, astroid.Module))
  128. for f in (frame, defframe)):
  129. # Not interested in other frames, since they are already
  130. # not in a global scope.
  131. return False
  132. break_scopes = []
  133. for s in (scope, def_scope):
  134. # Look for parent scopes. If there is anything different
  135. # than a module or a class scope, then they frames don't
  136. # share a global scope.
  137. parent_scope = s
  138. while parent_scope:
  139. if not isinstance(parent_scope, (astroid.ClassDef, astroid.Module)):
  140. break_scopes.append(parent_scope)
  141. break
  142. if parent_scope.parent:
  143. parent_scope = parent_scope.parent.scope()
  144. else:
  145. break
  146. if break_scopes and len(set(break_scopes)) != 1:
  147. # Store different scopes than expected.
  148. # If the stored scopes are, in fact, the very same, then it means
  149. # that the two frames (frame and defframe) shares the same scope,
  150. # and we could apply our lineno analysis over them.
  151. # For instance, this works when they are inside a function, the node
  152. # that uses a definition and the definition itself.
  153. return False
  154. # At this point, we are certain that frame and defframe shares a scope
  155. # and the definition of the first depends on the second.
  156. return frame.lineno < defframe.lineno
  157. def _fix_dot_imports(not_consumed):
  158. """ Try to fix imports with multiple dots, by returning a dictionary
  159. with the import names expanded. The function unflattens root imports,
  160. like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree'
  161. and 'xml.sax' respectively.
  162. """
  163. # TODO: this should be improved in issue astroid #46
  164. names = {}
  165. for name, stmts in six.iteritems(not_consumed):
  166. if any(isinstance(stmt, astroid.AssignName)
  167. and isinstance(stmt.assign_type(), astroid.AugAssign)
  168. for stmt in stmts):
  169. continue
  170. for stmt in stmts:
  171. if not isinstance(stmt, (astroid.ImportFrom, astroid.Import)):
  172. continue
  173. for imports in stmt.names:
  174. second_name = None
  175. if imports[0] == "*":
  176. # In case of wildcard imports,
  177. # pick the name from inside the imported module.
  178. second_name = name
  179. else:
  180. if imports[0].find(".") > -1 or name in imports:
  181. # Most likely something like 'xml.etree',
  182. # which will appear in the .locals as 'xml'.
  183. # Only pick the name if it wasn't consumed.
  184. second_name = imports[0]
  185. if second_name and second_name not in names:
  186. names[second_name] = stmt
  187. return sorted(names.items(), key=lambda a: a[1].fromlineno)
  188. def _find_frame_imports(name, frame):
  189. """
  190. Detect imports in the frame, with the required
  191. *name*. Such imports can be considered assignments.
  192. Returns True if an import for the given name was found.
  193. """
  194. imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
  195. for import_node in imports:
  196. for import_name, import_alias in import_node.names:
  197. # If the import uses an alias, check only that.
  198. # Otherwise, check only the import name.
  199. if import_alias:
  200. if import_alias == name:
  201. return True
  202. elif import_name and import_name == name:
  203. return True
  204. return None
  205. def _import_name_is_global(stmt, global_names):
  206. for import_name, import_alias in stmt.names:
  207. # If the import uses an alias, check only that.
  208. # Otherwise, check only the import name.
  209. if import_alias:
  210. if import_alias in global_names:
  211. return True
  212. elif import_name in global_names:
  213. return True
  214. return False
  215. def _flattened_scope_names(iterator):
  216. values = (set(stmt.names) for stmt in iterator)
  217. return set(itertools.chain.from_iterable(values))
  218. def _assigned_locally(name_node):
  219. """
  220. Checks if name_node has corresponding assign statement in same scope
  221. """
  222. assign_stmts = name_node.scope().nodes_of_class(astroid.AssignName)
  223. return any(a.name == name_node.name for a in assign_stmts)
  224. MSGS = {
  225. 'E0601': ('Using variable %r before assignment',
  226. 'used-before-assignment',
  227. 'Used when a local variable is accessed before it\'s \
  228. assignment.'),
  229. 'E0602': ('Undefined variable %r',
  230. 'undefined-variable',
  231. 'Used when an undefined variable is accessed.'),
  232. 'E0603': ('Undefined variable name %r in __all__',
  233. 'undefined-all-variable',
  234. 'Used when an undefined variable name is referenced in __all__.'),
  235. 'E0604': ('Invalid object %r in __all__, must contain only strings',
  236. 'invalid-all-object',
  237. 'Used when an invalid (non-string) object occurs in __all__.'),
  238. 'E0611': ('No name %r in module %r',
  239. 'no-name-in-module',
  240. 'Used when a name cannot be found in a module.'),
  241. 'W0601': ('Global variable %r undefined at the module level',
  242. 'global-variable-undefined',
  243. 'Used when a variable is defined through the "global" statement \
  244. but the variable is not defined in the module scope.'),
  245. 'W0602': ('Using global for %r but no assignment is done',
  246. 'global-variable-not-assigned',
  247. 'Used when a variable is defined through the "global" statement \
  248. but no assignment to this variable is done.'),
  249. 'W0603': ('Using the global statement', # W0121
  250. 'global-statement',
  251. 'Used when you use the "global" statement to update a global \
  252. variable. Pylint just try to discourage this \
  253. usage. That doesn\'t mean you cannot use it !'),
  254. 'W0604': ('Using the global statement at the module level', # W0103
  255. 'global-at-module-level',
  256. 'Used when you use the "global" statement at the module level \
  257. since it has no effect'),
  258. 'W0611': ('Unused %s',
  259. 'unused-import',
  260. 'Used when an imported module or variable is not used.'),
  261. 'W0612': ('Unused variable %r',
  262. 'unused-variable',
  263. 'Used when a variable is defined but not used.'),
  264. 'W0613': ('Unused argument %r',
  265. 'unused-argument',
  266. 'Used when a function or method argument is not used.'),
  267. 'W0614': ('Unused import %s from wildcard import',
  268. 'unused-wildcard-import',
  269. 'Used when an imported module or variable is not used from a \
  270. `\'from X import *\'` style import.'),
  271. 'W0621': ('Redefining name %r from outer scope (line %s)',
  272. 'redefined-outer-name',
  273. 'Used when a variable\'s name hides a name defined in the outer \
  274. scope.'),
  275. 'W0622': ('Redefining built-in %r',
  276. 'redefined-builtin',
  277. 'Used when a variable or function override a built-in.'),
  278. 'W0623': ('Redefining name %r from %s in exception handler',
  279. 'redefine-in-handler',
  280. 'Used when an exception handler assigns the exception \
  281. to an existing name'),
  282. 'W0631': ('Using possibly undefined loop variable %r',
  283. 'undefined-loop-variable',
  284. 'Used when an loop variable (i.e. defined by a for loop or \
  285. a list comprehension or a generator expression) is used outside \
  286. the loop.'),
  287. 'E0632': ('Possible unbalanced tuple unpacking with '
  288. 'sequence%s: '
  289. 'left side has %d label(s), right side has %d value(s)',
  290. 'unbalanced-tuple-unpacking',
  291. 'Used when there is an unbalanced tuple unpacking in assignment',
  292. {'old_names': [('W0632', 'unbalanced-tuple-unpacking')]}),
  293. 'E0633': ('Attempting to unpack a non-sequence%s',
  294. 'unpacking-non-sequence',
  295. 'Used when something which is not '
  296. 'a sequence is used in an unpack assignment',
  297. {'old_names': [('W0633', 'unpacking-non-sequence')]}),
  298. 'W0640': ('Cell variable %s defined in loop',
  299. 'cell-var-from-loop',
  300. 'A variable used in a closure is defined in a loop. '
  301. 'This will result in all closures using the same value for '
  302. 'the closed-over variable.'),
  303. }
  304. ScopeConsumer = collections.namedtuple("ScopeConsumer", "to_consume consumed scope_type")
  305. class NamesConsumer(object):
  306. """
  307. A simple class to handle consumed, to consume and scope type info of node locals
  308. """
  309. def __init__(self, node, scope_type):
  310. self._atomic = ScopeConsumer(copy.copy(node.locals), {}, scope_type)
  311. def __repr__(self):
  312. msg = "\nto_consume : {:s}\n".format(
  313. ", ".join(["{}->{}".format(key, val)
  314. for key, val in self._atomic.to_consume.items()]))
  315. msg += "consumed : {:s}\n".format(
  316. ", ".join(["{}->{}".format(key, val)
  317. for key, val in self._atomic.consumed.items()]))
  318. msg += "scope_type : {:s}\n".format(self._atomic.scope_type)
  319. return msg
  320. def __iter__(self):
  321. return iter(self._atomic)
  322. @property
  323. def to_consume(self):
  324. return self._atomic.to_consume
  325. @property
  326. def consumed(self):
  327. return self._atomic.consumed
  328. @property
  329. def scope_type(self):
  330. return self._atomic.scope_type
  331. def mark_as_consumed(self, name, new_node):
  332. """
  333. Mark the name as consumed and delete it from
  334. the to_consume dictionnary
  335. """
  336. self.consumed[name] = new_node
  337. del self.to_consume[name]
  338. def get_next_to_consume(self, node):
  339. # mark the name as consumed if it's defined in this scope
  340. name = node.name
  341. parent_node = node.parent
  342. found_node = self.to_consume.get(name)
  343. if (found_node and isinstance(parent_node, astroid.Assign)
  344. and parent_node == found_node[0].parent):
  345. lhs = found_node[0].parent.targets[0]
  346. if lhs.name == name: # this name is defined in this very statement
  347. found_node = None
  348. return found_node
  349. class VariablesChecker(BaseChecker):
  350. """checks for
  351. * unused variables / imports
  352. * undefined variables
  353. * redefinition of variable from builtins or from an outer scope
  354. * use of variable before assignment
  355. * __all__ consistency
  356. """
  357. __implements__ = IAstroidChecker
  358. name = 'variables'
  359. msgs = MSGS
  360. priority = -1
  361. options = (("init-import",
  362. {'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>',
  363. 'help' : 'Tells whether we should check for unused import in '
  364. '__init__ files.'}),
  365. ("dummy-variables-rgx",
  366. {'default': '_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_',
  367. 'type' :'regexp', 'metavar' : '<regexp>',
  368. 'help' : 'A regular expression matching the name of dummy '
  369. 'variables (i.e. expectedly not used).'}),
  370. ("additional-builtins",
  371. {'default': (), 'type' : 'csv',
  372. 'metavar' : '<comma separated list>',
  373. 'help' : 'List of additional names supposed to be defined in '
  374. 'builtins. Remember that you should avoid to define new builtins '
  375. 'when possible.'
  376. }),
  377. ("callbacks",
  378. {'default' : ('cb_', '_cb'), 'type' : 'csv',
  379. 'metavar' : '<callbacks>',
  380. 'help' : 'List of strings which can identify a callback '
  381. 'function by name. A callback name must start or '
  382. 'end with one of those strings.'}
  383. ),
  384. ("redefining-builtins-modules",
  385. {'default': ('six.moves', 'past.builtins', 'future.builtins', 'io', 'builtins'),
  386. 'type': 'csv',
  387. 'metavar': '<comma separated list>',
  388. 'help': 'List of qualified module names which can have objects '
  389. 'that can redefine builtins.'}
  390. ),
  391. ('ignored-argument-names',
  392. {'default' : IGNORED_ARGUMENT_NAMES,
  393. 'type' :'regexp', 'metavar' : '<regexp>',
  394. 'help' : 'Argument names that match this expression will be '
  395. 'ignored. Default to name with leading underscore'}
  396. ),
  397. ('allow-global-unused-variables',
  398. {'default': True,
  399. 'type': 'yn', 'metavar': '<y_or_n>',
  400. 'help': 'Tells whether unused global variables should be treated as a violation.'}
  401. ),
  402. )
  403. def __init__(self, linter=None):
  404. BaseChecker.__init__(self, linter)
  405. self._to_consume = None # list of tuples: (to_consume:dict, consumed:dict, scope_type:str)
  406. self._checking_mod_attr = None
  407. self._loop_variables = []
  408. # Relying on other checker's options, which might not have been initialized yet.
  409. @decorators.cachedproperty
  410. def _analyse_fallback_blocks(self):
  411. return get_global_option(self, 'analyse-fallback-blocks', default=False)
  412. @decorators.cachedproperty
  413. def _ignored_modules(self):
  414. return get_global_option(self, 'ignored-modules', default=[])
  415. @decorators.cachedproperty
  416. def _allow_global_unused_variables(self):
  417. return get_global_option(self, 'allow-global-unused-variables', default=True)
  418. @utils.check_messages('redefined-outer-name')
  419. def visit_for(self, node):
  420. assigned_to = [var.name for var in node.target.nodes_of_class(astroid.AssignName)]
  421. # Only check variables that are used
  422. dummy_rgx = self.config.dummy_variables_rgx
  423. assigned_to = [var for var in assigned_to if not dummy_rgx.match(var)]
  424. for variable in assigned_to:
  425. for outer_for, outer_variables in self._loop_variables:
  426. if (variable in outer_variables
  427. and not in_for_else_branch(outer_for, node)):
  428. self.add_message(
  429. 'redefined-outer-name',
  430. args=(variable, outer_for.fromlineno),
  431. node=node
  432. )
  433. break
  434. self._loop_variables.append((node, assigned_to))
  435. @utils.check_messages('redefined-outer-name')
  436. def leave_for(self, _):
  437. self._loop_variables.pop()
  438. def visit_module(self, node):
  439. """visit module : update consumption analysis variable
  440. checks globals doesn't overrides builtins
  441. """
  442. self._to_consume = [NamesConsumer(node, 'module')]
  443. for name, stmts in six.iteritems(node.locals):
  444. if utils.is_builtin(name) and not utils.is_inside_except(stmts[0]):
  445. if self._should_ignore_redefined_builtin(stmts[0]) or name == '__doc__':
  446. continue
  447. self.add_message('redefined-builtin', args=name, node=stmts[0])
  448. @utils.check_messages('unused-import', 'unused-wildcard-import',
  449. 'redefined-builtin', 'undefined-all-variable',
  450. 'invalid-all-object', 'unused-variable')
  451. def leave_module(self, node):
  452. """leave module: check globals
  453. """
  454. assert len(self._to_consume) == 1
  455. not_consumed = self._to_consume.pop().to_consume
  456. # attempt to check for __all__ if defined
  457. if '__all__' in node.locals:
  458. self._check_all(node, not_consumed)
  459. # check for unused globals
  460. self._check_globals(not_consumed)
  461. # don't check unused imports in __init__ files
  462. if not self.config.init_import and node.package:
  463. return
  464. self._check_imports(not_consumed)
  465. def _check_all(self, node, not_consumed):
  466. assigned = next(node.igetattr('__all__'))
  467. if assigned is astroid.YES:
  468. return
  469. for elt in getattr(assigned, 'elts', ()):
  470. try:
  471. elt_name = next(elt.infer())
  472. except astroid.InferenceError:
  473. continue
  474. if elt_name is astroid.Uninferable:
  475. continue
  476. if not elt_name.parent:
  477. continue
  478. if (not isinstance(elt_name, astroid.Const)
  479. or not isinstance(elt_name.value, six.string_types)):
  480. self.add_message('invalid-all-object',
  481. args=elt.as_string(), node=elt)
  482. continue
  483. elt_name = elt_name.value
  484. # If elt is in not_consumed, remove it from not_consumed
  485. if elt_name in not_consumed:
  486. del not_consumed[elt_name]
  487. continue
  488. if elt_name not in node.locals:
  489. if not node.package:
  490. self.add_message('undefined-all-variable',
  491. args=(elt_name, ),
  492. node=elt)
  493. else:
  494. basename = os.path.splitext(node.file)[0]
  495. if os.path.basename(basename) == '__init__':
  496. name = node.name + "." + elt_name
  497. try:
  498. modutils.file_from_modpath(name.split("."))
  499. except ImportError:
  500. self.add_message('undefined-all-variable',
  501. args=(elt_name, ),
  502. node=elt)
  503. except SyntaxError:
  504. # don't yield an syntax-error warning,
  505. # because it will be later yielded
  506. # when the file will be checked
  507. pass
  508. def _check_globals(self, not_consumed):
  509. if self._allow_global_unused_variables:
  510. return
  511. for name, nodes in six.iteritems(not_consumed):
  512. for node in nodes:
  513. self.add_message('unused-variable', args=(name,), node=node)
  514. def _check_imports(self, not_consumed):
  515. local_names = _fix_dot_imports(not_consumed)
  516. checked = set()
  517. for name, stmt in local_names:
  518. for imports in stmt.names:
  519. real_name = imported_name = imports[0]
  520. if imported_name == "*":
  521. real_name = name
  522. as_name = imports[1]
  523. if real_name in checked:
  524. continue
  525. if name not in (real_name, as_name):
  526. continue
  527. checked.add(real_name)
  528. if (isinstance(stmt, astroid.Import) or
  529. (isinstance(stmt, astroid.ImportFrom) and
  530. not stmt.modname)):
  531. if (isinstance(stmt, astroid.ImportFrom) and
  532. SPECIAL_OBJ.search(imported_name)):
  533. # Filter special objects (__doc__, __all__) etc.,
  534. # because they can be imported for exporting.
  535. continue
  536. if as_name == "_":
  537. continue
  538. if as_name is None:
  539. msg = "import %s" % imported_name
  540. else:
  541. msg = "%s imported as %s" % (imported_name, as_name)
  542. self.add_message('unused-import', args=msg, node=stmt)
  543. elif (isinstance(stmt, astroid.ImportFrom)
  544. and stmt.modname != FUTURE):
  545. if SPECIAL_OBJ.search(imported_name):
  546. # Filter special objects (__doc__, __all__) etc.,
  547. # because they can be imported for exporting.
  548. continue
  549. if _is_from_future_import(stmt, name):
  550. # Check if the name is in fact loaded from a
  551. # __future__ import in another module.
  552. continue
  553. if imported_name == '*':
  554. self.add_message('unused-wildcard-import',
  555. args=name, node=stmt)
  556. else:
  557. if as_name is None:
  558. msg = "%s imported from %s" % (imported_name, stmt.modname)
  559. else:
  560. fields = (imported_name, stmt.modname, as_name)
  561. msg = "%s imported from %s as %s" % fields
  562. self.add_message('unused-import', args=msg, node=stmt)
  563. del self._to_consume
  564. def visit_classdef(self, node):
  565. """visit class: update consumption analysis variable
  566. """
  567. self._to_consume.append(NamesConsumer(node, 'class'))
  568. def leave_classdef(self, _):
  569. """leave class: update consumption analysis variable
  570. """
  571. # do not check for not used locals here (no sense)
  572. self._to_consume.pop()
  573. def visit_lambda(self, node):
  574. """visit lambda: update consumption analysis variable
  575. """
  576. self._to_consume.append(NamesConsumer(node, 'lambda'))
  577. def leave_lambda(self, _):
  578. """leave lambda: update consumption analysis variable
  579. """
  580. # do not check for not used locals here
  581. self._to_consume.pop()
  582. def visit_generatorexp(self, node):
  583. """visit genexpr: update consumption analysis variable
  584. """
  585. self._to_consume.append(NamesConsumer(node, 'comprehension'))
  586. def leave_generatorexp(self, _):
  587. """leave genexpr: update consumption analysis variable
  588. """
  589. # do not check for not used locals here
  590. self._to_consume.pop()
  591. def visit_dictcomp(self, node):
  592. """visit dictcomp: update consumption analysis variable
  593. """
  594. self._to_consume.append(NamesConsumer(node, 'comprehension'))
  595. def leave_dictcomp(self, _):
  596. """leave dictcomp: update consumption analysis variable
  597. """
  598. # do not check for not used locals here
  599. self._to_consume.pop()
  600. def visit_setcomp(self, node):
  601. """visit setcomp: update consumption analysis variable
  602. """
  603. self._to_consume.append(NamesConsumer(node, 'comprehension'))
  604. def leave_setcomp(self, _):
  605. """leave setcomp: update consumption analysis variable
  606. """
  607. # do not check for not used locals here
  608. self._to_consume.pop()
  609. def visit_functiondef(self, node):
  610. """visit function: update consumption analysis variable and check locals
  611. """
  612. self._to_consume.append(NamesConsumer(node, 'function'))
  613. if not (self.linter.is_message_enabled('redefined-outer-name') or
  614. self.linter.is_message_enabled('redefined-builtin')):
  615. return
  616. globs = node.root().globals
  617. for name, stmt in node.items():
  618. if utils.is_inside_except(stmt):
  619. continue
  620. if name in globs and not isinstance(stmt, astroid.Global):
  621. definition = globs[name][0]
  622. if (isinstance(definition, astroid.ImportFrom)
  623. and definition.modname == FUTURE):
  624. # It is a __future__ directive, not a symbol.
  625. continue
  626. line = definition.fromlineno
  627. if not self._is_name_ignored(stmt, name):
  628. self.add_message('redefined-outer-name',
  629. args=(name, line), node=stmt)
  630. elif utils.is_builtin(name) and not self._should_ignore_redefined_builtin(stmt):
  631. # do not print Redefining builtin for additional builtins
  632. self.add_message('redefined-builtin', args=name, node=stmt)
  633. def _is_name_ignored(self, stmt, name):
  634. authorized_rgx = self.config.dummy_variables_rgx
  635. if (isinstance(stmt, astroid.AssignName)
  636. and isinstance(stmt.parent, astroid.Arguments)):
  637. regex = self.config.ignored_argument_names
  638. else:
  639. regex = authorized_rgx
  640. return regex and regex.match(name)
  641. def _check_is_unused(self, name, node, stmt, global_names, nonlocal_names):
  642. # Ignore some special names specified by user configuration.
  643. if self._is_name_ignored(stmt, name):
  644. return
  645. # Ignore names that were added dynamically to the Function scope
  646. if (isinstance(node, astroid.FunctionDef)
  647. and name == '__class__'
  648. and len(node.locals['__class__']) == 1
  649. and isinstance(node.locals['__class__'][0], astroid.ClassDef)):
  650. return
  651. # Ignore names imported by the global statement.
  652. # FIXME: should only ignore them if it's assigned latter
  653. if isinstance(stmt, astroid.Global):
  654. return
  655. if isinstance(stmt, (astroid.Import, astroid.ImportFrom)):
  656. # Detect imports, assigned to global statements.
  657. if global_names and _import_name_is_global(stmt, global_names):
  658. return
  659. argnames = list(itertools.chain(
  660. node.argnames(),
  661. [arg.name for arg in node.args.kwonlyargs]
  662. ))
  663. is_method = node.is_method()
  664. klass = node.parent.frame()
  665. if is_method and isinstance(klass, astroid.ClassDef):
  666. confidence = INFERENCE if utils.has_known_bases(klass) else INFERENCE_FAILURE
  667. else:
  668. confidence = HIGH
  669. # Care about functions with unknown argument (builtins)
  670. if name in argnames:
  671. if is_method:
  672. # Don't warn for the first argument of a (non static) method
  673. if node.type != 'staticmethod' and name == argnames[0]:
  674. return
  675. # Don't warn for argument of an overridden method
  676. overridden = overridden_method(klass, node.name)
  677. if overridden is not None and name in overridden.argnames():
  678. return
  679. if node.name in utils.PYMETHODS and node.name not in ('__init__', '__new__'):
  680. return
  681. # Don't check callback arguments
  682. if any(node.name.startswith(cb) or node.name.endswith(cb)
  683. for cb in self.config.callbacks):
  684. return
  685. # Don't check arguments of singledispatch.register function.
  686. if utils.is_registered_in_singledispatch_function(node):
  687. return
  688. self.add_message('unused-argument', args=name, node=stmt,
  689. confidence=confidence)
  690. else:
  691. if stmt.parent and isinstance(stmt.parent, astroid.Assign):
  692. if name in nonlocal_names:
  693. return
  694. if isinstance(stmt, astroid.Import):
  695. # Need the complete name, which we don't have in .locals.
  696. qname, asname = stmt.names[0]
  697. name = asname or qname
  698. self.add_message('unused-variable', args=name, node=stmt)
  699. def leave_functiondef(self, node):
  700. """leave function: check function's locals are consumed"""
  701. not_consumed = self._to_consume.pop().to_consume
  702. if not (self.linter.is_message_enabled('unused-variable') or
  703. self.linter.is_message_enabled('unused-argument')):
  704. return
  705. # Don't check arguments of function which are only raising an exception.
  706. if utils.is_error(node):
  707. return
  708. # Don't check arguments of abstract methods or within an interface.
  709. is_method = node.is_method()
  710. if is_method and node.is_abstract():
  711. return
  712. global_names = _flattened_scope_names(node.nodes_of_class(astroid.Global))
  713. nonlocal_names = _flattened_scope_names(node.nodes_of_class(astroid.Nonlocal))
  714. for name, stmts in six.iteritems(not_consumed):
  715. self._check_is_unused(name, node, stmts[0], global_names, nonlocal_names)
  716. visit_asyncfunctiondef = visit_functiondef
  717. leave_asyncfunctiondef = leave_functiondef
  718. @utils.check_messages('global-variable-undefined', 'global-variable-not-assigned',
  719. 'global-statement', 'global-at-module-level',
  720. 'redefined-builtin')
  721. def visit_global(self, node):
  722. """check names imported exists in the global scope"""
  723. frame = node.frame()
  724. if isinstance(frame, astroid.Module):
  725. self.add_message('global-at-module-level', node=node)
  726. return
  727. module = frame.root()
  728. default_message = True
  729. for name in node.names:
  730. try:
  731. assign_nodes = module.getattr(name)
  732. except astroid.NotFoundError:
  733. # unassigned global, skip
  734. assign_nodes = []
  735. if not assign_nodes:
  736. self.add_message('global-variable-not-assigned',
  737. args=name, node=node)
  738. default_message = False
  739. continue
  740. for anode in assign_nodes:
  741. if (isinstance(anode, astroid.AssignName)
  742. and anode.name in module.special_attributes):
  743. self.add_message('redefined-builtin', args=name, node=node)
  744. break
  745. if anode.frame() is module:
  746. # module level assignment
  747. break
  748. else:
  749. # global undefined at the module scope
  750. self.add_message('global-variable-undefined', args=name, node=node)
  751. default_message = False
  752. if default_message:
  753. self.add_message('global-statement', node=node)
  754. def _check_late_binding_closure(self, node, assignment_node):
  755. def _is_direct_lambda_call():
  756. return (isinstance(node_scope.parent, astroid.Call)
  757. and node_scope.parent.func is node_scope)
  758. node_scope = node.scope()
  759. if not isinstance(node_scope, (astroid.Lambda, astroid.FunctionDef)):
  760. return
  761. if isinstance(node.parent, astroid.Arguments):
  762. return
  763. if isinstance(assignment_node, astroid.Comprehension):
  764. if assignment_node.parent.parent_of(node.scope()):
  765. self.add_message('cell-var-from-loop', node=node, args=node.name)
  766. else:
  767. assign_scope = assignment_node.scope()
  768. maybe_for = assignment_node
  769. while not isinstance(maybe_for, astroid.For):
  770. if maybe_for is assign_scope:
  771. break
  772. maybe_for = maybe_for.parent
  773. else:
  774. if (maybe_for.parent_of(node_scope)
  775. and not _is_direct_lambda_call()
  776. and not isinstance(node_scope.statement(), astroid.Return)):
  777. self.add_message('cell-var-from-loop', node=node, args=node.name)
  778. def _loopvar_name(self, node, name):
  779. # filter variables according to node's scope
  780. # XXX used to filter parents but don't remember why, and removing this
  781. # fixes a W0631 false positive reported by Paul Hachmann on 2008/12 on
  782. # python-projects (added to func_use_for_or_listcomp_var test)
  783. #astmts = [stmt for stmt in node.lookup(name)[1]
  784. # if hasattr(stmt, 'ass_type')] and
  785. # not stmt.statement().parent_of(node)]
  786. if not self.linter.is_message_enabled('undefined-loop-variable'):
  787. return
  788. astmts = [stmt for stmt in node.lookup(name)[1]
  789. if hasattr(stmt, 'ass_type')]
  790. # filter variables according their respective scope test is_statement
  791. # and parent to avoid #74747. This is not a total fix, which would
  792. # introduce a mechanism similar to special attribute lookup in
  793. # modules. Also, in order to get correct inference in this case, the
  794. # scope lookup rules would need to be changed to return the initial
  795. # assignment (which does not exist in code per se) as well as any later
  796. # modifications.
  797. if not astmts or (astmts[0].is_statement or astmts[0].parent) \
  798. and astmts[0].statement().parent_of(node):
  799. _astmts = []
  800. else:
  801. _astmts = astmts[:1]
  802. for i, stmt in enumerate(astmts[1:]):
  803. if (astmts[i].statement().parent_of(stmt)
  804. and not in_for_else_branch(astmts[i].statement(), stmt)):
  805. continue
  806. _astmts.append(stmt)
  807. astmts = _astmts
  808. if len(astmts) == 1:
  809. assign = astmts[0].assign_type()
  810. if (isinstance(assign, (astroid.For, astroid.Comprehension,
  811. astroid.GeneratorExp))
  812. and assign.statement() is not node.statement()):
  813. self.add_message('undefined-loop-variable', args=name, node=node)
  814. def _should_ignore_redefined_builtin(self, stmt):
  815. if not isinstance(stmt, astroid.ImportFrom):
  816. return False
  817. return stmt.modname in self.config.redefining_builtins_modules
  818. @utils.check_messages('redefine-in-handler')
  819. def visit_excepthandler(self, node):
  820. for name in utils.get_all_elements(node.name):
  821. clobbering, args = utils.clobber_in_except(name)
  822. if clobbering:
  823. self.add_message('redefine-in-handler', args=args, node=name)
  824. def visit_assignname(self, node):
  825. if isinstance(node.assign_type(), astroid.AugAssign):
  826. self.visit_name(node)
  827. def visit_delname(self, node):
  828. self.visit_name(node)
  829. @staticmethod
  830. def _defined_in_function_definition(node, frame):
  831. in_annotation_or_default = False
  832. if (isinstance(frame, astroid.FunctionDef) and
  833. node.statement() is frame):
  834. in_annotation_or_default = (
  835. (
  836. PY3K and (node in frame.args.annotations
  837. or node in frame.args.kwonlyargs_annotations
  838. or node is frame.args.varargannotation
  839. or node is frame.args.kwargannotation)
  840. )
  841. or
  842. frame.args.parent_of(node)
  843. )
  844. return in_annotation_or_default
  845. @staticmethod
  846. def _is_variable_violation(node, name, defnode, stmt, defstmt,
  847. frame, defframe, base_scope_type,
  848. recursive_klass):
  849. # node: Node to check for violation
  850. # name: name of node to check violation for
  851. # frame: Scope of statement of node
  852. # base_scope_type: local scope type
  853. maybee0601 = True
  854. annotation_return = False
  855. use_outer_definition = False
  856. if frame is not defframe:
  857. maybee0601 = _detect_global_scope(node, frame, defframe)
  858. elif defframe.parent is None:
  859. # we are at the module level, check the name is not
  860. # defined in builtins
  861. if name in defframe.scope_attrs or astroid.builtin_lookup(name)[1]:
  862. maybee0601 = False
  863. else:
  864. # we are in a local scope, check the name is not
  865. # defined in global or builtin scope
  866. # skip this lookup if name is assigned later in function scope/lambda
  867. # Note: the node.frame() is not the same as the `frame` argument which is
  868. # equivalent to frame.statement().scope()
  869. forbid_lookup = ((isinstance(frame, astroid.FunctionDef) or
  870. isinstance(node.frame(), astroid.Lambda)) and
  871. _assigned_locally(node))
  872. if not forbid_lookup and defframe.root().lookup(name)[1]:
  873. maybee0601 = False
  874. use_outer_definition = (
  875. stmt == defstmt
  876. and not isinstance(defnode, astroid.node_classes.Comprehension)
  877. )
  878. else:
  879. # check if we have a nonlocal
  880. if name in defframe.locals:
  881. maybee0601 = not any(isinstance(child, astroid.Nonlocal)
  882. and name in child.names
  883. for child in defframe.get_children())
  884. if (base_scope_type == 'lambda' and
  885. isinstance(frame, astroid.ClassDef)
  886. and name in frame.locals):
  887. # This rule verifies that if the definition node of the
  888. # checked name is an Arguments node and if the name
  889. # is used a default value in the arguments defaults
  890. # and the actual definition of the variable label
  891. # is happening before the Arguments definition.
  892. #
  893. # bar = None
  894. # foo = lambda bar=bar: bar
  895. #
  896. # In this case, maybee0601 should be False, otherwise
  897. # it should be True.
  898. maybee0601 = not (isinstance(defnode, astroid.Arguments) and
  899. node in defnode.defaults and
  900. frame.locals[name][0].fromlineno < defstmt.fromlineno)
  901. elif (isinstance(defframe, astroid.ClassDef) and
  902. isinstance(frame, astroid.FunctionDef)):
  903. # Special rule for function return annotations,
  904. # which uses the same name as the class where
  905. # the function lives.
  906. if (PY3K and node is frame.returns and
  907. defframe.parent_of(frame.returns)):
  908. maybee0601 = annotation_return = True
  909. if (maybee0601 and defframe.name in defframe.locals and
  910. defframe.locals[name][0].lineno < frame.lineno):
  911. # Detect class assignments with the same
  912. # name as the class. In this case, no warning
  913. # should be raised.
  914. maybee0601 = False
  915. if isinstance(node.parent, astroid.Arguments):
  916. maybee0601 = stmt.fromlineno <= defstmt.fromlineno
  917. elif recursive_klass:
  918. maybee0601 = True
  919. else:
  920. maybee0601 = maybee0601 and stmt.fromlineno <= defstmt.fromlineno
  921. if maybee0601 and stmt.fromlineno == defstmt.fromlineno:
  922. if (isinstance(defframe, astroid.FunctionDef)
  923. and frame is defframe
  924. and defframe.parent_of(node)
  925. and stmt is not defstmt):
  926. # Single statement function, with the statement on the
  927. # same line as the function definition
  928. maybee0601 = False
  929. return maybee0601, annotation_return, use_outer_definition
  930. def _ignore_class_scope(self, node):
  931. """
  932. Return True if the node is in a local class scope, as an assignment.
  933. :param node: Node considered
  934. :type node: astroid.Node
  935. :return: True if the node is in a local class scope, as an assignment. False otherwise.
  936. :rtype: bool
  937. """
  938. # Detect if we are in a local class scope, as an assignment.
  939. # For example, the following is fair game.
  940. #
  941. # class A:
  942. # b = 1
  943. # c = lambda b=b: b * b
  944. #
  945. # class B:
  946. # tp = 1
  947. # def func(self, arg: tp):
  948. # ...
  949. # class C:
  950. # tp = 2
  951. # def func(self, arg=tp):
  952. # ...
  953. name = node.name
  954. frame = node.statement().scope()
  955. in_annotation_or_default = self._defined_in_function_definition(node, frame)
  956. if in_annotation_or_default:
  957. frame_locals = frame.parent.scope().locals
  958. else:
  959. frame_locals = frame.locals
  960. return not ((isinstance(frame, astroid.ClassDef) or in_annotation_or_default) and
  961. name in frame_locals)
  962. @utils.check_messages(*(MSGS.keys()))
  963. def visit_name(self, node):
  964. """check that a name is defined if the current scope and doesn't
  965. redefine a built-in
  966. """
  967. stmt = node.statement()
  968. if stmt.fromlineno is None:
  969. # name node from a astroid built from live code, skip
  970. assert not stmt.root().file.endswith('.py')
  971. return
  972. name = node.name
  973. frame = stmt.scope()
  974. # if the name node is used as a function default argument's value or as
  975. # a decorator, then start from the parent frame of the function instead
  976. # of the function frame - and thus open an inner class scope
  977. if ((utils.is_func_default(node) and not utils.in_comprehension(node)) or
  978. utils.is_func_decorator(node) or utils.is_ancestor_name(frame, node)):
  979. # Do not use the highest scope to look for variable name consumption in this case
  980. # If the name is used in the function default, or as a decorator, then it
  981. # cannot be defined there
  982. # (except for list comprehensions in function defaults)
  983. start_index = len(self._to_consume) - 2
  984. else:
  985. start_index = len(self._to_consume) - 1
  986. # iterates through parent scopes, from the inner to the outer
  987. base_scope_type = self._to_consume[start_index].scope_type
  988. # pylint: disable=too-many-nested-blocks; refactoring this block is a pain.
  989. for i in range(start_index, -1, -1):
  990. current_consumer = self._to_consume[i]
  991. # if the current scope is a class scope but it's not the inner
  992. # scope, ignore it. This prevents to access this scope instead of
  993. # the globals one in function members when there are some common
  994. # names. The only exception is when the starting scope is a
  995. # comprehension and its direct outer scope is a class
  996. if current_consumer.scope_type == 'class' and i != start_index and not (
  997. base_scope_type == 'comprehension' and i == start_index-1):
  998. if self._ignore_class_scope(node):
  999. continue
  1000. # the name has already been consumed, only check it's not a loop
  1001. # variable used outside the loop
  1002. # avoid the case where there are homonyms inside function scope and
  1003. # comprehension current scope (avoid bug #1731)
  1004. if name in current_consumer.consumed and not (
  1005. current_consumer.scope_type == 'comprehension'
  1006. and self._has_homonym_in_upper_function_scope(node, i)):
  1007. defnode = utils.assign_parent(current_consumer.consumed[name][0])
  1008. self._check_late_binding_closure(node, defnode)
  1009. self._loopvar_name(node, name)
  1010. break
  1011. found_node = current_consumer.get_next_to_consume(node)
  1012. if found_node is None:
  1013. continue
  1014. # checks for use before assignment
  1015. defnode = utils.assign_parent(current_consumer.to_consume[name][0])
  1016. if defnode is not None:
  1017. self._check_late_binding_closure(node, defnode)
  1018. defstmt = defnode.statement()
  1019. defframe = defstmt.frame()
  1020. # The class reuses itself in the class scope.
  1021. recursive_klass = (frame is defframe and
  1022. defframe.parent_of(node) and
  1023. isinstance(defframe, astroid.ClassDef) and
  1024. node.name == defframe.name)
  1025. maybee0601, annotation_return, use_outer_definition = self._is_variable_violation(
  1026. node, name, defnode, stmt, defstmt,
  1027. frame, defframe,
  1028. base_scope_type, recursive_klass)
  1029. if use_outer_definition:
  1030. continue
  1031. if (maybee0601
  1032. and not utils.is_defined_before(node)
  1033. and not astroid.are_exclusive(stmt, defstmt, ('NameError',))):
  1034. # Used and defined in the same place, e.g `x += 1` and `del x`
  1035. defined_by_stmt = (
  1036. defstmt is stmt
  1037. and isinstance(node, (astroid.DelName, astroid.AssignName))
  1038. )
  1039. if (recursive_klass
  1040. or defined_by_stmt
  1041. or annotation_return
  1042. or isinstance(defstmt, astroid.Delete)):
  1043. if not utils.node_ignores_exception(node, NameError):
  1044. self.add_message('undefined-variable', args=name,
  1045. node=node)
  1046. elif base_scope_type != 'lambda':
  1047. # E0601 may *not* occurs in lambda scope.
  1048. self.add_message('used-before-assignment', args=name, node=node)
  1049. elif base_scope_type == 'lambda':
  1050. # E0601 can occur in class-level scope in lambdas, as in
  1051. # the following example:
  1052. # class A:
  1053. # x = lambda attr: f + attr
  1054. # f = 42
  1055. if isinstance(frame, astroid.ClassDef) and name in frame.locals:
  1056. if isinstance(node.parent, astroid.Arguments):
  1057. if stmt.fromlineno <= defstmt.fromlineno:
  1058. # Doing the following is fine:
  1059. # class A:
  1060. # x = 42
  1061. # y = lambda attr=x: attr
  1062. self.add_message('used-before-assignment',
  1063. args=name, node=node)
  1064. else:
  1065. self.add_message('undefined-variable',
  1066. args=name, node=node)
  1067. elif current_consumer.scope_type == 'lambda':
  1068. self.add_message('undefined-variable',
  1069. node=node, args=name)
  1070. current_consumer.mark_as_consumed(name, found_node)
  1071. # check it's not a loop variable used outside the loop
  1072. self._loopvar_name(node, name)
  1073. break
  1074. else:
  1075. # we have not found the name, if it isn't a builtin, that's an
  1076. # undefined name !
  1077. if not (name in astroid.Module.scope_attrs or utils.is_builtin(name)
  1078. or name in self.config.additional_builtins):
  1079. if not utils.node_ignores_exception(node, NameError):
  1080. self.add_message('undefined-variable', args=name, node=node)
  1081. def _has_homonym_in_upper_function_scope(self, node, index):
  1082. """
  1083. Return True if there is a node with the same name in the to_consume dict of an upper scope
  1084. and if that scope is a function
  1085. :param node: node to check for
  1086. :type node: astroid.Node
  1087. :param index: index of the current consumer inside self._to_consume
  1088. :type index: int
  1089. :return: True if there is a node with the same name in the to_consume dict of a upper scope
  1090. and if that scope is a function
  1091. :rtype: bool
  1092. """
  1093. for _consumer in self._to_consume[index-1::-1]:
  1094. if _consumer.scope_type == 'function' and node.name in _consumer.to_consume:
  1095. return True
  1096. return False
  1097. @utils.check_messages('no-name-in-module')
  1098. def visit_import(self, node):
  1099. """check modules attribute accesses"""
  1100. if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
  1101. # No need to verify this, since ImportError is already
  1102. # handled by the client code.
  1103. return
  1104. for name, _ in node.names:
  1105. parts = name.split('.')
  1106. try:
  1107. module = next(node.infer_name_module(parts[0]))
  1108. except astroid.ResolveError:
  1109. continue
  1110. self._check_module_attrs(node, module, parts[1:])
  1111. @utils.check_messages('no-name-in-module')
  1112. def visit_importfrom(self, node):
  1113. """check modules attribute accesses"""
  1114. if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
  1115. # No need to verify this, since ImportError is already
  1116. # handled by the client code.
  1117. return
  1118. name_parts = node.modname.split('.')
  1119. try:
  1120. module = node.do_import_module(name_parts[0])
  1121. except astroid.AstroidBuildingException:
  1122. return
  1123. module = self._check_module_attrs(node, module, name_parts[1:])
  1124. if not module:
  1125. return
  1126. for name, _ in node.names:
  1127. if name == '*':
  1128. continue
  1129. self._check_module_attrs(node, module, name.split('.'))
  1130. @utils.check_messages('unbalanced-tuple-unpacking', 'unpacking-non-sequence')
  1131. def visit_assign(self, node):
  1132. """Check unbalanced tuple unpacking for assignments
  1133. and unpacking non-sequences.
  1134. """
  1135. if not isinstance(node.targets[0], (astroid.Tuple, astroid.List)):
  1136. return
  1137. targets = node.targets[0].itered()
  1138. try:
  1139. infered = utils.safe_infer(node.value)
  1140. if infered is not None:
  1141. self._check_unpacking(infered, node, targets)
  1142. except astroid.InferenceError:
  1143. return
  1144. def _check_unpacking(self, infered, node, targets):
  1145. """ Check for unbalanced tuple unpacking
  1146. and unpacking non sequences.
  1147. """
  1148. if utils.is_inside_abstract_class(node):
  1149. return
  1150. if utils.is_comprehension(node):
  1151. return
  1152. if infered is astroid.YES:
  1153. return
  1154. if (isinstance(infered.parent, astroid.Arguments) and
  1155. isinstance(node.value, astroid.Name) and
  1156. node.value.name == infered.parent.vararg):
  1157. # Variable-length argument, we can't determine the length.
  1158. return
  1159. if isinstance(infered, (astroid.Tuple, astroid.List)):
  1160. # attempt to check unpacking is properly balanced
  1161. values = infered.itered()
  1162. if len(targets) != len(values):
  1163. # Check if we have starred nodes.
  1164. if any(isinstance(target, astroid.Starred)
  1165. for target in targets):
  1166. return
  1167. self.add_message('unbalanced-tuple-unpacking', node=node,
  1168. args=(_get_unpacking_extra_info(node, infered),
  1169. len(targets),
  1170. len(values)))
  1171. # attempt to check unpacking may be possible (ie RHS is iterable)
  1172. else:
  1173. if not utils.is_iterable(infered):
  1174. self.add_message('unpacking-non-sequence', node=node,
  1175. args=(_get_unpacking_extra_info(node, infered),))
  1176. def _check_module_attrs(self, node, module, module_names):
  1177. """check that module_names (list of string) are accessible through the
  1178. given module
  1179. if the latest access name corresponds to a module, return it
  1180. """
  1181. assert isinstance(module, astroid.Module), module
  1182. while module_names:
  1183. name = module_names.pop(0)
  1184. if name == '__dict__':
  1185. module = None
  1186. break
  1187. try:
  1188. module = next(module.getattr(name)[0].infer())
  1189. if module is astroid.Uninferable:
  1190. return None
  1191. except astroid.NotFoundError:
  1192. if module.name in self._ignored_modules:
  1193. return None
  1194. self.add_message('no-name-in-module',
  1195. args=(name, module.name), node=node)
  1196. return None
  1197. except astroid.InferenceError:
  1198. return None
  1199. if module_names:
  1200. # FIXME: other message if name is not the latest part of
  1201. # module_names ?
  1202. modname = module.name if module else '__dict__'
  1203. self.add_message('no-name-in-module', node=node,
  1204. args=('.'.join(module_names), modname))
  1205. return None
  1206. if isinstance(module, astroid.Module):
  1207. return module
  1208. return None
  1209. class VariablesChecker3k(VariablesChecker):
  1210. '''Modified variables checker for 3k'''
  1211. # listcomp have now also their scope
  1212. def visit_listcomp(self, node):
  1213. """visit dictcomp: update consumption analysis variable
  1214. """
  1215. self._to_consume.append(NamesConsumer(node, 'comprehension'))
  1216. def leave_listcomp(self, _):
  1217. """leave dictcomp: update consumption analysis variable
  1218. """
  1219. # do not check for not used locals here
  1220. self._to_consume.pop()
  1221. def leave_functiondef(self, node):
  1222. self._check_metaclasses(node)
  1223. super(VariablesChecker3k, self).leave_functiondef(node)
  1224. def leave_module(self, node):
  1225. self._check_metaclasses(node)
  1226. super(VariablesChecker3k, self).leave_module(node)
  1227. def _check_metaclasses(self, node):
  1228. """ Update consumption analysis for metaclasses. """
  1229. consumed = [] # [(scope_locals, consumed_key)]
  1230. for child_node in node.get_children():
  1231. if isinstance(child_node, astroid.ClassDef):
  1232. consumed.extend(self._check_classdef_metaclasses(child_node, node))
  1233. # Pop the consumed items, in order to avoid having
  1234. # unused-import and unused-variable false positives
  1235. for scope_locals, name in consumed:
  1236. scope_locals.pop(name, None)
  1237. def _check_classdef_metaclasses(self, klass, parent_node):
  1238. if not klass._metaclass:
  1239. # Skip if this class doesn't use explicitly a metaclass, but inherits it from ancestors
  1240. return []
  1241. consumed = [] # [(scope_locals, consumed_key)]
  1242. metaclass = klass.metaclass()
  1243. name = None
  1244. if isinstance(klass._metaclass, astroid.Name):
  1245. name = klass._metaclass.name
  1246. elif metaclass:
  1247. name = metaclass.root().name
  1248. found = None
  1249. if name:
  1250. # check enclosing scopes starting from most local
  1251. for scope_locals, _, _ in self._to_consume[::-1]:
  1252. found = scope_locals.get(name)
  1253. if found:
  1254. consumed.append((scope_locals, name))
  1255. break
  1256. if found is None and not metaclass:
  1257. name = None
  1258. if isinstance(klass._metaclass, astroid.Name):
  1259. name = klass._metaclass.name
  1260. elif isinstance(klass._metaclass, astroid.Attribute):
  1261. name = klass._metaclass.as_string()
  1262. if name is not None:
  1263. if not (name in astroid.Module.scope_attrs or
  1264. utils.is_builtin(name) or
  1265. name in self.config.additional_builtins or
  1266. name in parent_node.locals):
  1267. self.add_message('undefined-variable',
  1268. node=klass,
  1269. args=(name,))
  1270. return consumed
  1271. if sys.version_info >= (3, 0):
  1272. VariablesChecker = VariablesChecker3k
  1273. def register(linter):
  1274. """required method to auto register this checker"""
  1275. linter.register_checker(VariablesChecker(linter))