newstyle.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
  4. """Check for new / old style related problems."""
  5. from __future__ import annotations
  6. from typing import TYPE_CHECKING
  7. import astroid
  8. from astroid import nodes
  9. from pylint.checkers import BaseChecker
  10. from pylint.checkers.utils import (
  11. has_known_bases,
  12. node_frame_class,
  13. only_required_for_messages,
  14. )
  15. from pylint.typing import MessageDefinitionTuple
  16. if TYPE_CHECKING:
  17. from pylint.lint import PyLinter
  18. MSGS: dict[str, MessageDefinitionTuple] = {
  19. "E1003": (
  20. "Bad first argument %r given to super()",
  21. "bad-super-call",
  22. "Used when another argument than the current class is given as "
  23. "first argument of the super builtin.",
  24. )
  25. }
  26. class NewStyleConflictChecker(BaseChecker):
  27. """Checks for usage of new style capabilities on old style classes and
  28. other new/old styles conflicts problems.
  29. * use of property, __slots__, super
  30. * "super" usage
  31. """
  32. # configuration section name
  33. name = "newstyle"
  34. # messages
  35. msgs = MSGS
  36. # configuration options
  37. options = ()
  38. @only_required_for_messages("bad-super-call")
  39. def visit_functiondef(self, node: nodes.FunctionDef) -> None:
  40. """Check use of super."""
  41. # ignore actual functions or method within a new style class
  42. if not node.is_method():
  43. return
  44. klass = node.parent.frame(future=True)
  45. for stmt in node.nodes_of_class(nodes.Call):
  46. if node_frame_class(stmt) != node_frame_class(node):
  47. # Don't look down in other scopes.
  48. continue
  49. expr = stmt.func
  50. if not isinstance(expr, nodes.Attribute):
  51. continue
  52. call = expr.expr
  53. # skip the test if using super
  54. if not (
  55. isinstance(call, nodes.Call)
  56. and isinstance(call.func, nodes.Name)
  57. and call.func.name == "super"
  58. ):
  59. continue
  60. # super should not be used on an old style class
  61. if klass.newstyle or not has_known_bases(klass):
  62. # super first arg should not be the class
  63. if not call.args:
  64. continue
  65. # calling super(type(self), self) can lead to recursion loop
  66. # in derived classes
  67. arg0 = call.args[0]
  68. if (
  69. isinstance(arg0, nodes.Call)
  70. and isinstance(arg0.func, nodes.Name)
  71. and arg0.func.name == "type"
  72. ):
  73. self.add_message("bad-super-call", node=call, args=("type",))
  74. continue
  75. # calling super(self.__class__, self) can lead to recursion loop
  76. # in derived classes
  77. if (
  78. len(call.args) >= 2
  79. and isinstance(call.args[1], nodes.Name)
  80. and call.args[1].name == "self"
  81. and isinstance(arg0, nodes.Attribute)
  82. and arg0.attrname == "__class__"
  83. ):
  84. self.add_message(
  85. "bad-super-call", node=call, args=("self.__class__",)
  86. )
  87. continue
  88. try:
  89. supcls = call.args and next(call.args[0].infer(), None)
  90. except astroid.InferenceError:
  91. continue
  92. # If the supcls is in the ancestors of klass super can be used to skip
  93. # a step in the mro() and get a method from a higher parent
  94. if klass is not supcls and all(i != supcls for i in klass.ancestors()):
  95. name = None
  96. # if supcls is not Uninferable, then supcls was inferred
  97. # and use its name. Otherwise, try to look
  98. # for call.args[0].name
  99. if supcls:
  100. name = supcls.name
  101. elif call.args and hasattr(call.args[0], "name"):
  102. name = call.args[0].name
  103. if name:
  104. self.add_message("bad-super-call", node=call, args=(name,))
  105. visit_asyncfunctiondef = visit_functiondef
  106. def register(linter: PyLinter) -> None:
  107. linter.register_checker(NewStyleConflictChecker(linter))