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.

emptystring.py 2.4KB

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_empty_str(node):
  13. return isinstance(node, astroid.Const) and node.value == ''
  14. class CompareToEmptyStringChecker(checkers.BaseChecker):
  15. """Checks for comparisons to empty string.
  16. Most of the times you should use the fact that empty strings are false.
  17. An exception to this rule is when an empty string value is allowed in the program
  18. and has a different meaning than None!
  19. """
  20. __implements__ = (interfaces.IAstroidChecker,)
  21. # configuration section name
  22. name = 'compare-to-empty-string'
  23. msgs = {'C1901': ('Avoid comparisons to empty string',
  24. 'compare-to-empty-string',
  25. 'Used when Pylint detects comparison to an empty string constant.'),
  26. }
  27. priority = -2
  28. options = ()
  29. @utils.check_messages('compare-to-empty-string')
  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. # x ?? ""
  45. if _is_constant_empty_str(op_1) and op_2 in _operators:
  46. error_detected = True
  47. # '' ?? X
  48. elif op_2 in _operators and _is_constant_empty_str(op_3):
  49. error_detected = True
  50. if error_detected:
  51. self.add_message('compare-to-empty-string', node=node)
  52. def register(linter):
  53. """Required method to auto register this checker."""
  54. linter.register_checker(CompareToEmptyStringChecker(linter))