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.

refactoring.py 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2016-2017 Claudiu Popa <pcmanticore@gmail.com>
  3. # Copyright (c) 2016-2017 Łukasz Rogalski <rogalski.91@gmail.com>
  4. # Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
  5. # Copyright (c) 2016 Alexander Todorov <atodorov@otb.bg>
  6. # Copyright (c) 2017-2018 hippo91 <guillaume.peillex@gmail.com>
  7. # Copyright (c) 2017 Hugo <hugovk@users.noreply.github.com>
  8. # Copyright (c) 2017 Bryce Guinta <bryce.paul.guinta@gmail.com>
  9. # Copyright (c) 2017 Łukasz Sznuk <ls@rdprojekt.pl>
  10. # Copyright (c) 2017 Alex Hearn <alex.d.hearn@gmail.com>
  11. # Copyright (c) 2017 Antonio Ossa <aaossa@uc.cl>
  12. # Copyright (c) 2017 Ville Skyttä <ville.skytta@iki.fi>
  13. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  14. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  15. """Looks for code which can be refactored."""
  16. import collections
  17. import itertools
  18. import tokenize
  19. import astroid
  20. from astroid import decorators
  21. import six
  22. from pylint import interfaces
  23. from pylint import checkers
  24. from pylint import utils as lint_utils
  25. from pylint.checkers import utils
  26. def _all_elements_are_true(gen):
  27. values = list(gen)
  28. return values and all(values)
  29. def _if_statement_is_always_returning(if_node):
  30. def _has_return_node(elems, scope):
  31. for node in elems:
  32. if isinstance(node, astroid.If):
  33. yield _if_statement_is_always_returning(node)
  34. elif isinstance(node, astroid.Return):
  35. yield node.scope() is scope
  36. scope = if_node.scope()
  37. body_returns = _all_elements_are_true(
  38. _has_return_node(if_node.body, scope=scope)
  39. )
  40. if if_node.orelse:
  41. orelse_returns = _all_elements_are_true(
  42. _has_return_node(if_node.orelse, scope=scope)
  43. )
  44. else:
  45. orelse_returns = False
  46. return body_returns and orelse_returns
  47. class RefactoringChecker(checkers.BaseTokenChecker):
  48. """Looks for code which can be refactored
  49. This checker also mixes the astroid and the token approaches
  50. in order to create knowledge about whether a "else if" node
  51. is a true "else if" node, or a "elif" node.
  52. """
  53. __implements__ = (interfaces.ITokenChecker, interfaces.IAstroidChecker)
  54. name = 'refactoring'
  55. msgs = {
  56. 'R1701': ("Consider merging these isinstance calls to isinstance(%s, (%s))",
  57. "consider-merging-isinstance",
  58. "Used when multiple consecutive isinstance calls can be merged into one."),
  59. 'R1706': ("Consider using ternary (%s)",
  60. "consider-using-ternary",
  61. "Used when one of known pre-python 2.5 ternary syntax is used.",),
  62. 'R1709': ("Boolean expression may be simplified to %s",
  63. "simplify-boolean-expression",
  64. "Emitted when redundant pre-python 2.5 ternary syntax is used.",),
  65. 'R1702': ('Too many nested blocks (%s/%s)',
  66. 'too-many-nested-blocks',
  67. 'Used when a function or a method has too many nested '
  68. 'blocks. This makes the code less understandable and '
  69. 'maintainable.',
  70. {'old_names': [('R0101', 'too-many-nested-blocks')]}),
  71. 'R1703': ('The if statement can be replaced with %s',
  72. 'simplifiable-if-statement',
  73. 'Used when an if statement can be replaced with '
  74. '\'bool(test)\'. ',
  75. {'old_names': [('R0102', 'simplifiable-if-statement')]}),
  76. 'R1704': ('Redefining argument with the local name %r',
  77. 'redefined-argument-from-local',
  78. 'Used when a local name is redefining an argument, which might '
  79. 'suggest a potential error. This is taken in account only for '
  80. 'a handful of name binding operations, such as for iteration, '
  81. 'with statement assignment and exception handler assignment.'
  82. ),
  83. 'R1705': ('Unnecessary "else" after "return"',
  84. 'no-else-return',
  85. 'Used in order to highlight an unnecessary block of '
  86. 'code following an if containing a return statement. '
  87. 'As such, it will warn when it encounters an else '
  88. 'following a chain of ifs, all of them containing a '
  89. 'return statement.'
  90. ),
  91. 'R1707': ('Disallow trailing comma tuple',
  92. 'trailing-comma-tuple',
  93. 'In Python, a tuple is actually created by the comma symbol, '
  94. 'not by the parentheses. Unfortunately, one can actually create a '
  95. 'tuple by misplacing a trailing comma, which can lead to potential '
  96. 'weird bugs in your code. You should always use parentheses '
  97. 'explicitly for creating a tuple.',
  98. {'minversion': (3, 0)}),
  99. 'R1708': ('Do not raise StopIteration in generator, use return statement instead',
  100. 'stop-iteration-return',
  101. 'According to PEP479, the raise of StopIteration to end the loop of '
  102. 'a generator may lead to hard to find bugs. This PEP specify that '
  103. 'raise StopIteration has to be replaced by a simple return statement',
  104. {'minversion': (3, 0)}),
  105. 'R1710': ('Either all return statements in a function should return an expression, '
  106. 'or none of them should.',
  107. 'inconsistent-return-statements',
  108. 'According to PEP8, if any return statement returns an expression, '
  109. 'any return statements where no value is returned should explicitly '
  110. 'state this as return None, and an explicit return statement '
  111. 'should be present at the end of the function (if reachable)'
  112. ),
  113. }
  114. options = (('max-nested-blocks',
  115. {'default': 5, 'type': 'int', 'metavar': '<int>',
  116. 'help': 'Maximum number of nested blocks for function / '
  117. 'method body'}
  118. ),
  119. ('never-returning-functions',
  120. {'default': ('optparse.Values', 'sys.exit',),
  121. 'type': 'csv',
  122. 'help': 'Complete name of functions that never returns. When checking '
  123. 'for inconsistent-return-statements if a never returning function is '
  124. 'called then it will be considered as an explicit return statement '
  125. 'and no message will be printed.'}
  126. ),)
  127. priority = 0
  128. def __init__(self, linter=None):
  129. checkers.BaseTokenChecker.__init__(self, linter)
  130. self._return_nodes = {}
  131. self._init()
  132. self._never_returning_functions = None
  133. def _init(self):
  134. self._nested_blocks = []
  135. self._elifs = []
  136. self._nested_blocks_msg = None
  137. def open(self):
  138. # do this in open since config not fully initialized in __init__
  139. self._never_returning_functions = set(self.config.never_returning_functions)
  140. @decorators.cachedproperty
  141. def _dummy_rgx(self):
  142. return lint_utils.get_global_option(
  143. self, 'dummy-variables-rgx', default=None)
  144. @staticmethod
  145. def _is_bool_const(node):
  146. return (isinstance(node.value, astroid.Const)
  147. and isinstance(node.value.value, bool))
  148. def _is_actual_elif(self, node):
  149. """Check if the given node is an actual elif
  150. This is a problem we're having with the builtin ast module,
  151. which splits `elif` branches into a separate if statement.
  152. Unfortunately we need to know the exact type in certain
  153. cases.
  154. """
  155. if isinstance(node.parent, astroid.If):
  156. orelse = node.parent.orelse
  157. # current if node must directly follow a "else"
  158. if orelse and orelse == [node]:
  159. if (node.lineno, node.col_offset) in self._elifs:
  160. return True
  161. return False
  162. def _check_simplifiable_if(self, node):
  163. """Check if the given if node can be simplified.
  164. The if statement can be reduced to a boolean expression
  165. in some cases. For instance, if there are two branches
  166. and both of them return a boolean value that depends on
  167. the result of the statement's test, then this can be reduced
  168. to `bool(test)` without losing any functionality.
  169. """
  170. if self._is_actual_elif(node):
  171. # Not interested in if statements with multiple branches.
  172. return
  173. if len(node.orelse) != 1 or len(node.body) != 1:
  174. return
  175. # Check if both branches can be reduced.
  176. first_branch = node.body[0]
  177. else_branch = node.orelse[0]
  178. if isinstance(first_branch, astroid.Return):
  179. if not isinstance(else_branch, astroid.Return):
  180. return
  181. first_branch_is_bool = self._is_bool_const(first_branch)
  182. else_branch_is_bool = self._is_bool_const(else_branch)
  183. reduced_to = "'return bool(test)'"
  184. elif isinstance(first_branch, astroid.Assign):
  185. if not isinstance(else_branch, astroid.Assign):
  186. return
  187. first_branch_is_bool = self._is_bool_const(first_branch)
  188. else_branch_is_bool = self._is_bool_const(else_branch)
  189. reduced_to = "'var = bool(test)'"
  190. else:
  191. return
  192. if not first_branch_is_bool or not else_branch_is_bool:
  193. return
  194. if not first_branch.value.value:
  195. # This is a case that can't be easily simplified and
  196. # if it can be simplified, it will usually result in a
  197. # code that's harder to understand and comprehend.
  198. # Let's take for instance `arg and arg <= 3`. This could theoretically be
  199. # reduced to `not arg or arg > 3`, but the net result is that now the
  200. # condition is harder to understand, because it requires understanding of
  201. # an extra clause:
  202. # * first, there is the negation of truthness with `not arg`
  203. # * the second clause is `arg > 3`, which occurs when arg has a
  204. # a truth value, but it implies that `arg > 3` is equivalent
  205. # with `arg and arg > 3`, which means that the user must
  206. # think about this assumption when evaluating `arg > 3`.
  207. # The original form is easier to grasp.
  208. return
  209. self.add_message('simplifiable-if-statement', node=node,
  210. args=(reduced_to,))
  211. def process_tokens(self, tokens):
  212. # Process tokens and look for 'if' or 'elif'
  213. for index, token in enumerate(tokens):
  214. token_string = token[1]
  215. if token_string == 'elif':
  216. # AST exists by the time process_tokens is called, so
  217. # it's safe to assume tokens[index+1]
  218. # exists. tokens[index+1][2] is the elif's position as
  219. # reported by CPython and PyPy,
  220. # tokens[index][2] is the actual position and also is
  221. # reported by IronPython.
  222. self._elifs.extend([tokens[index][2], tokens[index+1][2]])
  223. elif six.PY3 and is_trailing_comma(tokens, index):
  224. if self.linter.is_message_enabled('trailing-comma-tuple'):
  225. self.add_message('trailing-comma-tuple',
  226. line=token.start[0])
  227. def leave_module(self, _):
  228. self._init()
  229. @utils.check_messages('too-many-nested-blocks')
  230. def visit_tryexcept(self, node):
  231. self._check_nested_blocks(node)
  232. visit_tryfinally = visit_tryexcept
  233. visit_while = visit_tryexcept
  234. def _check_redefined_argument_from_local(self, name_node):
  235. if self._dummy_rgx and self._dummy_rgx.match(name_node.name):
  236. return
  237. if not name_node.lineno:
  238. # Unknown position, maybe it is a manually built AST?
  239. return
  240. scope = name_node.scope()
  241. if not isinstance(scope, astroid.FunctionDef):
  242. return
  243. for defined_argument in scope.args.nodes_of_class(astroid.AssignName):
  244. if defined_argument.name == name_node.name:
  245. self.add_message('redefined-argument-from-local',
  246. node=name_node,
  247. args=(name_node.name, ))
  248. @utils.check_messages('redefined-argument-from-local',
  249. 'too-many-nested-blocks')
  250. def visit_for(self, node):
  251. self._check_nested_blocks(node)
  252. for name in node.target.nodes_of_class(astroid.AssignName):
  253. self._check_redefined_argument_from_local(name)
  254. @utils.check_messages('redefined-argument-from-local')
  255. def visit_excepthandler(self, node):
  256. if node.name and isinstance(node.name, astroid.AssignName):
  257. self._check_redefined_argument_from_local(node.name)
  258. @utils.check_messages('redefined-argument-from-local')
  259. def visit_with(self, node):
  260. for _, names in node.items:
  261. if not names:
  262. continue
  263. for name in names.nodes_of_class(astroid.AssignName):
  264. self._check_redefined_argument_from_local(name)
  265. def _check_superfluous_else_return(self, node):
  266. if not node.orelse:
  267. # Not interested in if statements without else.
  268. return
  269. if _if_statement_is_always_returning(node) and not self._is_actual_elif(node):
  270. self.add_message('no-else-return', node=node)
  271. @utils.check_messages('too-many-nested-blocks', 'simplifiable-if-statement',
  272. 'no-else-return',)
  273. def visit_if(self, node):
  274. self._check_simplifiable_if(node)
  275. self._check_nested_blocks(node)
  276. self._check_superfluous_else_return(node)
  277. @utils.check_messages('too-many-nested-blocks', 'inconsistent-return-statements')
  278. def leave_functiondef(self, node):
  279. # check left-over nested blocks stack
  280. self._emit_nested_blocks_message_if_needed(self._nested_blocks)
  281. # new scope = reinitialize the stack of nested blocks
  282. self._nested_blocks = []
  283. # check consistent return statements
  284. self._check_consistent_returns(node)
  285. self._return_nodes[node.name] = []
  286. @utils.check_messages('stop-iteration-return')
  287. def visit_raise(self, node):
  288. self._check_stop_iteration_inside_generator(node)
  289. def _check_stop_iteration_inside_generator(self, node):
  290. """Check if an exception of type StopIteration is raised inside a generator"""
  291. frame = node.frame()
  292. if not isinstance(frame, astroid.FunctionDef) or not frame.is_generator():
  293. return
  294. if utils.node_ignores_exception(node, StopIteration):
  295. return
  296. if not node.exc:
  297. return
  298. exc = utils.safe_infer(node.exc)
  299. if exc is None or exc is astroid.Uninferable:
  300. return
  301. if self._check_exception_inherit_from_stopiteration(exc):
  302. self.add_message('stop-iteration-return', node=node)
  303. @staticmethod
  304. def _check_exception_inherit_from_stopiteration(exc):
  305. """Return True if the exception node in argument inherit from StopIteration"""
  306. stopiteration_qname = '{}.StopIteration'.format(utils.EXCEPTIONS_MODULE)
  307. return any(_class.qname() == stopiteration_qname for _class in exc.mro())
  308. @utils.check_messages('stop-iteration-return')
  309. def visit_call(self, node):
  310. self._check_raising_stopiteration_in_generator_next_call(node)
  311. def _check_raising_stopiteration_in_generator_next_call(self, node):
  312. """Check if a StopIteration exception is raised by the call to next function"""
  313. inferred = utils.safe_infer(node.func)
  314. if getattr(inferred, 'name', '') == 'next':
  315. frame = node.frame()
  316. if (isinstance(frame, astroid.FunctionDef) and frame.is_generator()
  317. and not utils.node_ignores_exception(node, StopIteration)):
  318. self.add_message('stop-iteration-return', node=node)
  319. def _check_nested_blocks(self, node):
  320. """Update and check the number of nested blocks
  321. """
  322. # only check block levels inside functions or methods
  323. if not isinstance(node.scope(), astroid.FunctionDef):
  324. return
  325. # messages are triggered on leaving the nested block. Here we save the
  326. # stack in case the current node isn't nested in the previous one
  327. nested_blocks = self._nested_blocks[:]
  328. if node.parent == node.scope():
  329. self._nested_blocks = [node]
  330. else:
  331. # go through ancestors from the most nested to the less
  332. for ancestor_node in reversed(self._nested_blocks):
  333. if ancestor_node == node.parent:
  334. break
  335. self._nested_blocks.pop()
  336. # if the node is a elif, this should not be another nesting level
  337. if isinstance(node, astroid.If) and self._is_actual_elif(node):
  338. if self._nested_blocks:
  339. self._nested_blocks.pop()
  340. self._nested_blocks.append(node)
  341. # send message only once per group of nested blocks
  342. if len(nested_blocks) > len(self._nested_blocks):
  343. self._emit_nested_blocks_message_if_needed(nested_blocks)
  344. def _emit_nested_blocks_message_if_needed(self, nested_blocks):
  345. if len(nested_blocks) > self.config.max_nested_blocks:
  346. self.add_message('too-many-nested-blocks', node=nested_blocks[0],
  347. args=(len(nested_blocks), self.config.max_nested_blocks))
  348. @staticmethod
  349. def _duplicated_isinstance_types(node):
  350. """Get the duplicated types from the underlying isinstance calls.
  351. :param astroid.BoolOp node: Node which should contain a bunch of isinstance calls.
  352. :returns: Dictionary of the comparison objects from the isinstance calls,
  353. to duplicate values from consecutive calls.
  354. :rtype: dict
  355. """
  356. duplicated_objects = set()
  357. all_types = collections.defaultdict(set)
  358. for call in node.values:
  359. if not isinstance(call, astroid.Call) or len(call.args) != 2:
  360. continue
  361. inferred = utils.safe_infer(call.func)
  362. if not inferred or not utils.is_builtin_object(inferred):
  363. continue
  364. if inferred.name != 'isinstance':
  365. continue
  366. isinstance_object = call.args[0].as_string()
  367. isinstance_types = call.args[1]
  368. if isinstance_object in all_types:
  369. duplicated_objects.add(isinstance_object)
  370. if isinstance(isinstance_types, astroid.Tuple):
  371. elems = [class_type.as_string() for class_type in isinstance_types.itered()]
  372. else:
  373. elems = [isinstance_types.as_string()]
  374. all_types[isinstance_object].update(elems)
  375. # Remove all keys which not duplicated
  376. return {key: value for key, value in all_types.items()
  377. if key in duplicated_objects}
  378. @utils.check_messages('consider-merging-isinstance')
  379. def visit_boolop(self, node):
  380. '''Check isinstance calls which can be merged together.'''
  381. if node.op != 'or':
  382. return
  383. first_args = self._duplicated_isinstance_types(node)
  384. for duplicated_name, class_names in first_args.items():
  385. names = sorted(name for name in class_names)
  386. self.add_message('consider-merging-isinstance',
  387. node=node,
  388. args=(duplicated_name, ', '.join(names)))
  389. @utils.check_messages('simplify-boolean-expression', 'consider-using-ternary')
  390. def visit_assign(self, node):
  391. if self._is_and_or_ternary(node.value):
  392. cond, truth_value, false_value = self._and_or_ternary_arguments(node.value)
  393. elif self._is_seq_based_ternary(node.value):
  394. cond, truth_value, false_value = self._seq_based_ternary_params(node.value)
  395. else:
  396. return
  397. if truth_value.bool_value() is False:
  398. message = 'simplify-boolean-expression'
  399. suggestion = false_value.as_string()
  400. else:
  401. message = 'consider-using-ternary'
  402. suggestion = '{truth} if {cond} else {false}'.format(
  403. truth=truth_value.as_string(),
  404. cond=cond.as_string(),
  405. false=false_value.as_string()
  406. )
  407. self.add_message(message, node=node, args=(suggestion,))
  408. visit_return = visit_assign
  409. @staticmethod
  410. def _is_and_or_ternary(node):
  411. """
  412. Returns true if node is 'condition and true_value else false_value' form.
  413. All of: condition, true_value and false_value should not be a complex boolean expression
  414. """
  415. return (isinstance(node, astroid.BoolOp)
  416. and node.op == 'or' and len(node.values) == 2
  417. and isinstance(node.values[0], astroid.BoolOp)
  418. and not isinstance(node.values[1], astroid.BoolOp)
  419. and node.values[0].op == 'and'
  420. and not isinstance(node.values[0].values[1], astroid.BoolOp)
  421. and len(node.values[0].values) == 2)
  422. @staticmethod
  423. def _and_or_ternary_arguments(node):
  424. false_value = node.values[1]
  425. condition, true_value = node.values[0].values
  426. return condition, true_value, false_value
  427. @staticmethod
  428. def _is_seq_based_ternary(node):
  429. """Returns true if node is '[false_value,true_value][condition]' form"""
  430. return (isinstance(node, astroid.Subscript)
  431. and isinstance(node.value, (astroid.Tuple, astroid.List))
  432. and len(node.value.elts) == 2 and isinstance(node.slice, astroid.Index))
  433. @staticmethod
  434. def _seq_based_ternary_params(node):
  435. false_value, true_value = node.value.elts
  436. condition = node.slice.value
  437. return condition, true_value, false_value
  438. def visit_functiondef(self, node):
  439. self._return_nodes[node.name] = []
  440. return_nodes = node.nodes_of_class(astroid.Return)
  441. self._return_nodes[node.name] = [_rnode for _rnode in return_nodes
  442. if _rnode.frame() == node.frame()]
  443. def _check_consistent_returns(self, node):
  444. """Check that all return statements inside a function are consistent.
  445. Return statements are consistent if:
  446. - all returns are explicit and if there is no implicit return;
  447. - all returns are empty and if there is, possibly, an implicit return.
  448. Args:
  449. node (astroid.FunctionDef): the function holding the return statements.
  450. """
  451. # explicit return statements are those with a not None value
  452. explicit_returns = [_node for _node in self._return_nodes[node.name]
  453. if _node.value is not None]
  454. if not explicit_returns:
  455. return
  456. if (len(explicit_returns) == len(self._return_nodes[node.name])
  457. and self._is_node_return_ended(node)):
  458. return
  459. self.add_message('inconsistent-return-statements', node=node)
  460. def _is_node_return_ended(self, node):
  461. """Check if the node ends with an explicit return statement.
  462. Args:
  463. node (astroid.NodeNG): node to be checked.
  464. Returns:
  465. bool: True if the node ends with an explicit statement, False otherwise.
  466. """
  467. # Recursion base case
  468. if isinstance(node, astroid.Return):
  469. return True
  470. if isinstance(node, astroid.Call):
  471. try:
  472. funcdef_node = node.func.infered()[0]
  473. if self._is_function_def_never_returning(funcdef_node):
  474. return True
  475. except astroid.InferenceError:
  476. pass
  477. # Avoid the check inside while loop as we don't know
  478. # if they will be completed
  479. if isinstance(node, astroid.While):
  480. return True
  481. if isinstance(node, astroid.Raise):
  482. # a Raise statement doesn't need to end with a return statement
  483. # but if the exception raised is handled, then the handler has to
  484. # ends with a return statement
  485. if not node.exc:
  486. # Ignore bare raises
  487. return True
  488. if not utils.is_node_inside_try_except(node):
  489. # If the raise statement is not inside a try/except statement
  490. # then the exception is raised and cannot be caught. No need
  491. # to infer it.
  492. return True
  493. exc = utils.safe_infer(node.exc)
  494. if exc is None or exc is astroid.Uninferable:
  495. return False
  496. exc_name = exc.pytype().split('.')[-1]
  497. handlers = utils.get_exception_handlers(node, exc_name)
  498. handlers = list(handlers) if handlers is not None else []
  499. if handlers:
  500. # among all the handlers handling the exception at least one
  501. # must end with a return statement
  502. return any(self._is_node_return_ended(_handler) for _handler in handlers)
  503. # if no handlers handle the exception then it's ok
  504. return True
  505. if isinstance(node, astroid.If):
  506. # if statement is returning if there are exactly two return statements in its
  507. # children : one for the body part, the other for the orelse part
  508. # Do not check if inner function definition are return ended.
  509. return_stmts = [self._is_node_return_ended(_child) for _child in node.get_children()
  510. if not isinstance(_child, astroid.FunctionDef)]
  511. return sum(return_stmts) == 2
  512. # recurses on the children of the node except for those which are except handler
  513. # because one cannot be sure that the handler will really be used
  514. return any(self._is_node_return_ended(_child) for _child in node.get_children()
  515. if not isinstance(_child, astroid.ExceptHandler))
  516. def _is_function_def_never_returning(self, node):
  517. """Return True if the function never returns. False otherwise.
  518. Args:
  519. node (astroid.FunctionDef): function definition node to be analyzed.
  520. Returns:
  521. bool: True if the function never returns, False otherwise.
  522. """
  523. try:
  524. return node.qname() in self._never_returning_functions
  525. except TypeError:
  526. return False
  527. class RecommandationChecker(checkers.BaseChecker):
  528. __implements__ = (interfaces.IAstroidChecker,)
  529. name = 'refactoring'
  530. msgs = {'C0200': ('Consider using enumerate instead of iterating with range and len',
  531. 'consider-using-enumerate',
  532. 'Emitted when code that iterates with range and len is '
  533. 'encountered. Such code can be simplified by using the '
  534. 'enumerate builtin.'),
  535. 'C0201': ('Consider iterating the dictionary directly instead of calling .keys()',
  536. 'consider-iterating-dictionary',
  537. 'Emitted when the keys of a dictionary are iterated through the .keys() '
  538. 'method. It is enough to just iterate through the dictionary itself, as '
  539. 'in "for key in dictionary".'),
  540. }
  541. @staticmethod
  542. def _is_builtin(node, function):
  543. inferred = utils.safe_infer(node)
  544. if not inferred:
  545. return False
  546. return utils.is_builtin_object(inferred) and inferred.name == function
  547. @utils.check_messages('consider-iterating-dictionary')
  548. def visit_call(self, node):
  549. inferred = utils.safe_infer(node.func)
  550. if not inferred:
  551. return
  552. if not isinstance(inferred, astroid.BoundMethod):
  553. return
  554. if not isinstance(inferred.bound, astroid.Dict) or inferred.name != 'keys':
  555. return
  556. if isinstance(node.parent, (astroid.For, astroid.Comprehension)):
  557. self.add_message('consider-iterating-dictionary', node=node)
  558. @utils.check_messages('consider-using-enumerate')
  559. def visit_for(self, node):
  560. """Emit a convention whenever range and len are used for indexing."""
  561. # Verify that we have a `range([start], len(...), [stop])` call and
  562. # that the object which is iterated is used as a subscript in the
  563. # body of the for.
  564. # Is it a proper range call?
  565. if not isinstance(node.iter, astroid.Call):
  566. return
  567. if not self._is_builtin(node.iter.func, 'range'):
  568. return
  569. if len(node.iter.args) == 2 and not _is_constant_zero(node.iter.args[0]):
  570. return
  571. if len(node.iter.args) > 2:
  572. return
  573. # Is it a proper len call?
  574. if not isinstance(node.iter.args[-1], astroid.Call):
  575. return
  576. second_func = node.iter.args[-1].func
  577. if not self._is_builtin(second_func, 'len'):
  578. return
  579. len_args = node.iter.args[-1].args
  580. if not len_args or len(len_args) != 1:
  581. return
  582. iterating_object = len_args[0]
  583. if not isinstance(iterating_object, astroid.Name):
  584. return
  585. # Verify that the body of the for loop uses a subscript
  586. # with the object that was iterated. This uses some heuristics
  587. # in order to make sure that the same object is used in the
  588. # for body.
  589. for child in node.body:
  590. for subscript in child.nodes_of_class(astroid.Subscript):
  591. if not isinstance(subscript.value, astroid.Name):
  592. continue
  593. if not isinstance(subscript.slice, astroid.Index):
  594. continue
  595. if not isinstance(subscript.slice.value, astroid.Name):
  596. continue
  597. if subscript.slice.value.name != node.target.name:
  598. continue
  599. if iterating_object.name != subscript.value.name:
  600. continue
  601. if subscript.value.scope() != node.scope():
  602. # Ignore this subscript if it's not in the same
  603. # scope. This means that in the body of the for
  604. # loop, another scope was created, where the same
  605. # name for the iterating object was used.
  606. continue
  607. self.add_message('consider-using-enumerate', node=node)
  608. return
  609. class NotChecker(checkers.BaseChecker):
  610. """checks for too many not in comparison expressions
  611. - "not not" should trigger a warning
  612. - "not" followed by a comparison should trigger a warning
  613. """
  614. __implements__ = (interfaces.IAstroidChecker,)
  615. msgs = {'C0113': ('Consider changing "%s" to "%s"',
  616. 'unneeded-not',
  617. 'Used when a boolean expression contains an unneeded '
  618. 'negation.'),
  619. }
  620. name = 'basic'
  621. reverse_op = {'<': '>=', '<=': '>', '>': '<=', '>=': '<', '==': '!=',
  622. '!=': '==', 'in': 'not in', 'is': 'is not'}
  623. # sets are not ordered, so for example "not set(LEFT_VALS) <= set(RIGHT_VALS)" is
  624. # not equivalent to "set(LEFT_VALS) > set(RIGHT_VALS)"
  625. skipped_nodes = (astroid.Set,)
  626. # 'builtins' py3, '__builtin__' py2
  627. skipped_classnames = ['%s.%s' % (six.moves.builtins.__name__, qname)
  628. for qname in ('set', 'frozenset')]
  629. @utils.check_messages('unneeded-not')
  630. def visit_unaryop(self, node):
  631. if node.op != 'not':
  632. return
  633. operand = node.operand
  634. if isinstance(operand, astroid.UnaryOp) and operand.op == 'not':
  635. self.add_message('unneeded-not', node=node,
  636. args=(node.as_string(),
  637. operand.operand.as_string()))
  638. elif isinstance(operand, astroid.Compare):
  639. left = operand.left
  640. # ignore multiple comparisons
  641. if len(operand.ops) > 1:
  642. return
  643. operator, right = operand.ops[0]
  644. if operator not in self.reverse_op:
  645. return
  646. # Ignore __ne__ as function of __eq__
  647. frame = node.frame()
  648. if frame.name == '__ne__' and operator == '==':
  649. return
  650. for _type in (utils.node_type(left), utils.node_type(right)):
  651. if not _type:
  652. return
  653. if isinstance(_type, self.skipped_nodes):
  654. return
  655. if (isinstance(_type, astroid.Instance) and
  656. _type.qname() in self.skipped_classnames):
  657. return
  658. suggestion = '%s %s %s' % (left.as_string(),
  659. self.reverse_op[operator],
  660. right.as_string())
  661. self.add_message('unneeded-not', node=node,
  662. args=(node.as_string(), suggestion))
  663. def _is_len_call(node):
  664. """Checks if node is len(SOMETHING)."""
  665. return (isinstance(node, astroid.Call) and isinstance(node.func, astroid.Name) and
  666. node.func.name == 'len')
  667. def _is_constant_zero(node):
  668. return isinstance(node, astroid.Const) and node.value == 0
  669. def _node_is_test_condition(node):
  670. """ Checks if node is an if, while, assert or if expression statement."""
  671. return isinstance(node, (astroid.If, astroid.While, astroid.Assert, astroid.IfExp))
  672. class LenChecker(checkers.BaseChecker):
  673. """Checks for incorrect usage of len() inside conditions.
  674. Pep8 states:
  675. For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
  676. Yes: if not seq:
  677. if seq:
  678. No: if len(seq):
  679. if not len(seq):
  680. Problems detected:
  681. * if len(sequence):
  682. * if not len(sequence):
  683. * if len(sequence) == 0:
  684. * if len(sequence) != 0:
  685. * if len(sequence) > 0:
  686. """
  687. __implements__ = (interfaces.IAstroidChecker,)
  688. # configuration section name
  689. name = 'len'
  690. msgs = {'C1801': ('Do not use `len(SEQUENCE)` to determine if a sequence is empty',
  691. 'len-as-condition',
  692. 'Used when Pylint detects that len(sequence) is being used inside '
  693. 'a condition to determine if a sequence is empty. Instead of '
  694. 'comparing the length to 0, rely on the fact that empty sequences '
  695. 'are false.'),
  696. }
  697. priority = -2
  698. options = ()
  699. @utils.check_messages('len-as-condition')
  700. def visit_call(self, node):
  701. # a len(S) call is used inside a test condition
  702. # could be if, while, assert or if expression statement
  703. # e.g. `if len(S):`
  704. if _is_len_call(node):
  705. # the len() call could also be nested together with other
  706. # boolean operations, e.g. `if z or len(x):`
  707. parent = node.parent
  708. while isinstance(parent, astroid.BoolOp):
  709. parent = parent.parent
  710. # we're finally out of any nested boolean operations so check if
  711. # this len() call is part of a test condition
  712. if not _node_is_test_condition(parent):
  713. return
  714. if not (node is parent.test or parent.test.parent_of(node)):
  715. return
  716. self.add_message('len-as-condition', node=node)
  717. @utils.check_messages('len-as-condition')
  718. def visit_unaryop(self, node):
  719. """`not len(S)` must become `not S` regardless if the parent block
  720. is a test condition or something else (boolean expression)
  721. e.g. `if not len(S):`"""
  722. if isinstance(node, astroid.UnaryOp) and node.op == 'not' and _is_len_call(node.operand):
  723. self.add_message('len-as-condition', node=node)
  724. @utils.check_messages('len-as-condition')
  725. def visit_compare(self, node):
  726. # compare nodes are trickier because the len(S) expression
  727. # may be somewhere in the middle of the node
  728. # note: astroid.Compare has the left most operand in node.left
  729. # while the rest are a list of tuples in node.ops
  730. # the format of the tuple is ('compare operator sign', node)
  731. # here we squash everything into `ops` to make it easier for processing later
  732. ops = [('', node.left)]
  733. ops.extend(node.ops)
  734. ops = list(itertools.chain(*ops))
  735. for ops_idx in range(len(ops) - 2):
  736. op_1 = ops[ops_idx]
  737. op_2 = ops[ops_idx + 1]
  738. op_3 = ops[ops_idx + 2]
  739. error_detected = False
  740. # 0 ?? len()
  741. if _is_constant_zero(op_1) and op_2 in ['==', '!=', '<'] and _is_len_call(op_3):
  742. error_detected = True
  743. # len() ?? 0
  744. elif _is_len_call(op_1) and op_2 in ['==', '!=', '>'] and _is_constant_zero(op_3):
  745. error_detected = True
  746. if error_detected:
  747. parent = node.parent
  748. # traverse the AST to figure out if this comparison was part of
  749. # a test condition
  750. while parent and not _node_is_test_condition(parent):
  751. parent = parent.parent
  752. # report only if this len() comparison is part of a test condition
  753. # for example: return len() > 0 should not report anything
  754. if _node_is_test_condition(parent):
  755. self.add_message('len-as-condition', node=node)
  756. def is_trailing_comma(tokens, index):
  757. """Check if the given token is a trailing comma
  758. :param tokens: Sequence of modules tokens
  759. :type tokens: list[tokenize.TokenInfo]
  760. :param int index: Index of token under check in tokens
  761. :returns: True if the token is a comma which trails an expression
  762. :rtype: bool
  763. """
  764. token = tokens[index]
  765. if token.exact_type != tokenize.COMMA:
  766. return False
  767. # Must have remaining tokens on the same line such as NEWLINE
  768. left_tokens = itertools.islice(tokens, index + 1, None)
  769. same_line_remaining_tokens = list(itertools.takewhile(
  770. lambda other_token, _token=token: other_token.start[0] == _token.start[0],
  771. left_tokens
  772. ))
  773. # Note: If the newline is tokenize.NEWLINE and not tokenize.NL
  774. # then the newline denotes the end of expression
  775. is_last_element = all(
  776. other_token.type in (tokenize.NEWLINE, tokenize.COMMENT)
  777. for other_token in same_line_remaining_tokens
  778. )
  779. if not same_line_remaining_tokens or not is_last_element:
  780. return False
  781. def get_curline_index_start():
  782. """Get the index denoting the start of the current line"""
  783. for subindex, token in enumerate(reversed(tokens[:index])):
  784. # See Lib/tokenize.py and Lib/token.py in cpython for more info
  785. if token.type in (tokenize.NEWLINE, tokenize.NL):
  786. return index - subindex
  787. return 0
  788. curline_start = get_curline_index_start()
  789. for prevtoken in tokens[curline_start:index]:
  790. if '=' in prevtoken.string:
  791. return True
  792. return False
  793. def register(linter):
  794. """Required method to auto register this checker."""
  795. linter.register_checker(RefactoringChecker(linter))
  796. linter.register_checker(NotChecker(linter))
  797. linter.register_checker(RecommandationChecker(linter))
  798. linter.register_checker(LenChecker(linter))