functools.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Plugin for supporting the functools standard library module."""
  2. from __future__ import annotations
  3. from typing import NamedTuple
  4. from typing_extensions import Final
  5. import mypy.plugin
  6. from mypy.nodes import ARG_POS, ARG_STAR2, Argument, FuncItem, Var
  7. from mypy.plugins.common import add_method_to_class
  8. from mypy.types import AnyType, CallableType, Type, TypeOfAny, UnboundType, get_proper_type
  9. functools_total_ordering_makers: Final = {"functools.total_ordering"}
  10. _ORDERING_METHODS: Final = {"__lt__", "__le__", "__gt__", "__ge__"}
  11. class _MethodInfo(NamedTuple):
  12. is_static: bool
  13. type: CallableType
  14. def functools_total_ordering_maker_callback(
  15. ctx: mypy.plugin.ClassDefContext, auto_attribs_default: bool = False
  16. ) -> bool:
  17. """Add dunder methods to classes decorated with functools.total_ordering."""
  18. comparison_methods = _analyze_class(ctx)
  19. if not comparison_methods:
  20. ctx.api.fail(
  21. 'No ordering operation defined when using "functools.total_ordering": < > <= >=',
  22. ctx.reason,
  23. )
  24. return True
  25. # prefer __lt__ to __le__ to __gt__ to __ge__
  26. root = max(comparison_methods, key=lambda k: (comparison_methods[k] is None, k))
  27. root_method = comparison_methods[root]
  28. if not root_method:
  29. # None of the defined comparison methods can be analysed
  30. return True
  31. other_type = _find_other_type(root_method)
  32. bool_type = ctx.api.named_type("builtins.bool")
  33. ret_type: Type = bool_type
  34. if root_method.type.ret_type != ctx.api.named_type("builtins.bool"):
  35. proper_ret_type = get_proper_type(root_method.type.ret_type)
  36. if not (
  37. isinstance(proper_ret_type, UnboundType)
  38. and proper_ret_type.name.split(".")[-1] == "bool"
  39. ):
  40. ret_type = AnyType(TypeOfAny.implementation_artifact)
  41. for additional_op in _ORDERING_METHODS:
  42. # Either the method is not implemented
  43. # or has an unknown signature that we can now extrapolate.
  44. if not comparison_methods.get(additional_op):
  45. args = [Argument(Var("other", other_type), other_type, None, ARG_POS)]
  46. add_method_to_class(ctx.api, ctx.cls, additional_op, args, ret_type)
  47. return True
  48. def _find_other_type(method: _MethodInfo) -> Type:
  49. """Find the type of the ``other`` argument in a comparison method."""
  50. first_arg_pos = 0 if method.is_static else 1
  51. cur_pos_arg = 0
  52. other_arg = None
  53. for arg_kind, arg_type in zip(method.type.arg_kinds, method.type.arg_types):
  54. if arg_kind.is_positional():
  55. if cur_pos_arg == first_arg_pos:
  56. other_arg = arg_type
  57. break
  58. cur_pos_arg += 1
  59. elif arg_kind != ARG_STAR2:
  60. other_arg = arg_type
  61. break
  62. if other_arg is None:
  63. return AnyType(TypeOfAny.implementation_artifact)
  64. return other_arg
  65. def _analyze_class(ctx: mypy.plugin.ClassDefContext) -> dict[str, _MethodInfo | None]:
  66. """Analyze the class body, its parents, and return the comparison methods found."""
  67. # Traverse the MRO and collect ordering methods.
  68. comparison_methods: dict[str, _MethodInfo | None] = {}
  69. # Skip object because total_ordering does not use methods from object
  70. for cls in ctx.cls.info.mro[:-1]:
  71. for name in _ORDERING_METHODS:
  72. if name in cls.names and name not in comparison_methods:
  73. node = cls.names[name].node
  74. if isinstance(node, FuncItem) and isinstance(node.type, CallableType):
  75. comparison_methods[name] = _MethodInfo(node.is_static, node.type)
  76. continue
  77. if isinstance(node, Var):
  78. proper_type = get_proper_type(node.type)
  79. if isinstance(proper_type, CallableType):
  80. comparison_methods[name] = _MethodInfo(node.is_staticmethod, proper_type)
  81. continue
  82. comparison_methods[name] = None
  83. return comparison_methods