functools.py 3.9 KB

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