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.

comparetozero.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2016 Alexander Todorov <atodorov@otb.bg>
  3. # Copyright (c) 2017 Claudiu Popa <pcmanticore@gmail.com>
  4. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  5. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  6. """Looks for comparisons to empty string."""
  7. import itertools
  8. import astroid
  9. from pylint import interfaces
  10. from pylint import checkers
  11. from pylint.checkers import utils
  12. def _is_constant_zero(node):
  13. return isinstance(node, astroid.Const) and node.value == 0
  14. class CompareToZeroChecker(checkers.BaseChecker):
  15. """Checks for comparisons to zero.
  16. Most of the times you should use the fact that integers with a value of 0 are false.
  17. An exception to this rule is when 0 is allowed in the program and has a
  18. different meaning than None!
  19. """
  20. __implements__ = (interfaces.IAstroidChecker,)
  21. # configuration section name
  22. name = 'compare-to-zero'
  23. msgs = {'C2001': ('Avoid comparisons to zero',
  24. 'compare-to-zero',
  25. 'Used when Pylint detects comparison to a 0 constant.'),
  26. }
  27. priority = -2
  28. options = ()
  29. @utils.check_messages('compare-to-zero')
  30. def visit_compare(self, node):
  31. _operators = ['!=', '==', 'is not', 'is']
  32. # note: astroid.Compare has the left most operand in node.left
  33. # while the rest are a list of tuples in node.ops
  34. # the format of the tuple is ('compare operator sign', node)
  35. # here we squash everything into `ops` to make it easier for processing later
  36. ops = [('', node.left)]
  37. ops.extend(node.ops)
  38. ops = list(itertools.chain(*ops))
  39. for ops_idx in range(len(ops) - 2):
  40. op_1 = ops[ops_idx]
  41. op_2 = ops[ops_idx + 1]
  42. op_3 = ops[ops_idx + 2]
  43. error_detected = False
  44. # 0 ?? X
  45. if _is_constant_zero(op_1) and op_2 in _operators + ['<']:
  46. error_detected = True
  47. # X ?? 0
  48. elif op_2 in _operators + ['>'] and _is_constant_zero(op_3):
  49. error_detected = True
  50. if error_detected:
  51. self.add_message('compare-to-zero', node=node)
  52. def register(linter):
  53. """Required method to auto register this checker."""
  54. linter.register_checker(CompareToZeroChecker(linter))