bad_builtin.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. """Checker for deprecated builtins."""
  5. from __future__ import annotations
  6. from typing import TYPE_CHECKING
  7. from astroid import nodes
  8. from pylint.checkers import BaseChecker
  9. from pylint.checkers.utils import only_required_for_messages
  10. if TYPE_CHECKING:
  11. from pylint.lint import PyLinter
  12. BAD_FUNCTIONS = ["map", "filter"]
  13. # Some hints regarding the use of bad builtins.
  14. LIST_COMP_MSG = "Using a list comprehension can be clearer."
  15. BUILTIN_HINTS = {"map": LIST_COMP_MSG, "filter": LIST_COMP_MSG}
  16. class BadBuiltinChecker(BaseChecker):
  17. name = "deprecated_builtins"
  18. msgs = {
  19. "W0141": (
  20. "Used builtin function %s",
  21. "bad-builtin",
  22. "Used when a disallowed builtin function is used (see the "
  23. "bad-function option). Usual disallowed functions are the ones "
  24. "like map, or filter , where Python offers now some cleaner "
  25. "alternative like list comprehension.",
  26. )
  27. }
  28. options = (
  29. (
  30. "bad-functions",
  31. {
  32. "default": BAD_FUNCTIONS,
  33. "type": "csv",
  34. "metavar": "<builtin function names>",
  35. "help": "List of builtins function names that should not be "
  36. "used, separated by a comma",
  37. },
  38. ),
  39. )
  40. @only_required_for_messages("bad-builtin")
  41. def visit_call(self, node: nodes.Call) -> None:
  42. if isinstance(node.func, nodes.Name):
  43. name = node.func.name
  44. # ignore the name if it's not a builtin (i.e. not defined in the
  45. # locals nor globals scope)
  46. if not (name in node.frame(future=True) or name in node.root()):
  47. if name in self.linter.config.bad_functions:
  48. hint = BUILTIN_HINTS.get(name)
  49. args = f"{name!r}. {hint}" if hint else repr(name)
  50. self.add_message("bad-builtin", node=node, args=args)
  51. def register(linter: PyLinter) -> None:
  52. linter.register_checker(BadBuiltinChecker(linter))