bad_builtin.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (c) 2016, 2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
  2. # Copyright (c) 2019, 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  3. # Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.github.com>
  4. # Copyright (c) 2020 Peter Kolbus <peter.kolbus@gmail.com>
  5. # Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
  6. # Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
  7. # Copyright (c) 2021 Nick Drozd <nicholasdrozd@gmail.com>
  8. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  9. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  10. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  11. """Checker for deprecated builtins."""
  12. from astroid import nodes
  13. from pylint.checkers import BaseChecker
  14. from pylint.checkers.utils import check_messages
  15. from pylint.interfaces import IAstroidChecker
  16. BAD_FUNCTIONS = ["map", "filter"]
  17. # Some hints regarding the use of bad builtins.
  18. BUILTIN_HINTS = {"map": "Using a list comprehension can be clearer."}
  19. BUILTIN_HINTS["filter"] = BUILTIN_HINTS["map"]
  20. class BadBuiltinChecker(BaseChecker):
  21. __implements__ = (IAstroidChecker,)
  22. name = "deprecated_builtins"
  23. msgs = {
  24. "W0141": (
  25. "Used builtin function %s",
  26. "bad-builtin",
  27. "Used when a disallowed builtin function is used (see the "
  28. "bad-function option). Usual disallowed functions are the ones "
  29. "like map, or filter , where Python offers now some cleaner "
  30. "alternative like list comprehension.",
  31. )
  32. }
  33. options = (
  34. (
  35. "bad-functions",
  36. {
  37. "default": BAD_FUNCTIONS,
  38. "type": "csv",
  39. "metavar": "<builtin function names>",
  40. "help": "List of builtins function names that should not be "
  41. "used, separated by a comma",
  42. },
  43. ),
  44. )
  45. @check_messages("bad-builtin")
  46. def visit_call(self, node: nodes.Call) -> None:
  47. if isinstance(node.func, nodes.Name):
  48. name = node.func.name
  49. # ignore the name if it's not a builtin (i.e. not defined in the
  50. # locals nor globals scope)
  51. if not (name in node.frame() or name in node.root()):
  52. if name in self.config.bad_functions:
  53. hint = BUILTIN_HINTS.get(name)
  54. args = f"{name!r}. {hint}" if hint else repr(name)
  55. self.add_message("bad-builtin", node=node, args=args)
  56. def register(linter):
  57. """Required method to auto register this checker.
  58. :param linter: Main interface object for Pylint plugins
  59. :type linter: Pylint object
  60. """
  61. linter.register_checker(BadBuiltinChecker(linter))