diff --git a/mypy/checker.py b/mypy/checker.py index ea7adc757d1d..9cc8dea5e0ef 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -2004,6 +2004,19 @@ def check___new___signature(self, fdef: FuncDef, typ: CallableType) -> None: "but must return a subtype of", ) + def is_ternary_rpow(self, reverse_type: CallableType, reverse_name: str) -> bool: + """Is this a three-argument __rpow__, which ternary pow() calls since Python 3.14?""" + if reverse_name != "__rpow__" or self.options.python_version < (3, 14): + return False + ternary_type = CallableType( + [AnyType(TypeOfAny.special_form)] * 3, + [nodes.ARG_POS] * 3, + [None] * 3, + AnyType(TypeOfAny.special_form), + self.named_type("builtins.function"), + ) + return is_subtype(reverse_type, ternary_type) + def check_reverse_op_method( self, defn: FuncItem, reverse_type: CallableType, reverse_name: str, context: Context ) -> None: @@ -2024,7 +2037,9 @@ def check_reverse_op_method( AnyType(TypeOfAny.special_form), self.named_type("builtins.function"), ) - if not is_subtype(reverse_type, method_type): + if not is_subtype(reverse_type, method_type) and not self.is_ternary_rpow( + reverse_type, reverse_name + ): self.msg.invalid_signature(reverse_type, context) return diff --git a/test-data/unit/check-classes.test b/test-data/unit/check-classes.test index 48910c0e64ce..c07fd48360b5 100644 --- a/test-data/unit/check-classes.test +++ b/test-data/unit/check-classes.test @@ -2509,6 +2509,35 @@ class C: tmp/foo.pyi:3: error: Invalid signature "Callable[[B], A]" tmp/foo.pyi:5: error: Invalid signature "Callable[[C, Any, Any], int]" +[case testReverseOperatorTernaryRpow] +# flags: --python-version 3.14 +from typing import overload +class A: + @overload + def __rpow__(self, other: int) -> A: ... + @overload + def __rpow__(self, other: int, mod: int) -> A: ... + def __rpow__(self, other: int, mod: int | None = None) -> A: ... +class B: + def __radd__(self, other: int, mod: int) -> B: ... +reveal_type(2 ** A()) # N: Revealed type is "__main__.A" +[builtins fixtures/ops.pyi] +[out] +main:10: error: Invalid signature "Callable[[B, int, int], B]" + +[case testReverseOperatorTernaryRpowBefore314] +# flags: --python-version 3.13 +from typing import overload +class A: + @overload + def __rpow__(self, other: int) -> A: ... + @overload + def __rpow__(self, other: int, mod: int) -> A: ... + def __rpow__(self, other: int, mod: int | None = None) -> A: ... +[builtins fixtures/ops.pyi] +[out] +main:7: error: Invalid signature "Callable[[A, int, int], A]" + [case testReverseOperatorOrderingCase1] class A: def __radd__(self, other: 'A') -> int: ...