Skip to content

Commit bd109f7

Browse files
committed
Only consider typevars same type after deeper comparison - we already have other places that create same-id copies of typevars
1 parent 7104782 commit bd109f7

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

mypy/subtypes.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -264,15 +264,17 @@ def is_same_type(
264264
a non-simplified union) but are semantically exchangeable in all contexts.
265265
"""
266266
# First, use fast path for some common types. This is performance-critical.
267-
if (
267+
if a is b:
268+
return True
269+
elif (
268270
type(a) is Instance
269271
and type(b) is Instance
270272
and a.type == b.type
271273
and len(a.args) == len(b.args)
272274
and a.last_known_value is b.last_known_value
273275
):
274276
return all(is_same_type(x, y) for x, y in zip(a.args, b.args))
275-
elif isinstance(a, TypeVarType) and isinstance(b, TypeVarType) and a.id == b.id:
277+
elif a == b:
276278
return True
277279

278280
# Note that using ignore_promotions=True (default) makes types like int and int64

test-data/unit/check-expressions.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,21 @@ def check(x: _T, y: _T) -> bool:
731731
return x < y
732732
[builtins fixtures/ops.pyi]
733733

734+
[case testReversibleOpOnTypeVarProtocol]
735+
# https://github.com/python/mypy/issues/18203
736+
from typing import Protocol, TypeVar, Union
737+
from typing_extensions import Self
738+
739+
class A(Protocol):
740+
def __add__(self, other: Union[int, Self]) -> Self: ...
741+
def __radd__(self, other: Union[int, Self]) -> Self: ...
742+
743+
AT = TypeVar("AT", bound=Union[int, A])
744+
745+
def f(a: AT, _b: AT) -> None:
746+
a + a
747+
[builtins fixtures/ops.pyi]
748+
734749

735750
[case testErrorContextAndBinaryOperators]
736751
import typing

0 commit comments

Comments
 (0)