Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reject promotions when checking against protocols. #18360

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ def visit_instance(self, left: Instance) -> bool:
return True
if type_state.is_cached_negative_subtype_check(self._subtype_kind, left, right):
return False
if not self.subtype_context.ignore_promotions:
if not self.subtype_context.ignore_promotions and not right.type.is_protocol:
for base in left.type.mro:
if base._promote and any(
self._is_subtype(p, self.right) for p in base._promote
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-type-promotion.test
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,19 @@ if isinstance(x, (float, complex)):
else:
reveal_type(x) # N: Revealed type is "builtins.int"
[builtins fixtures/primitives.pyi]

[case testRejectPromotionsForProtocols]
from typing import Protocol

class H(Protocol):
def hex(self, /) -> str: ...

f: H = 1.0
o: H = object() # E: Incompatible types in assignment (expression has type "object", variable has type "H")
c: H = 1j # E: Incompatible types in assignment (expression has type "complex", variable has type "H")
i: H = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "H")
b: H = False # E: Incompatible types in assignment (expression has type "bool", variable has type "H")

class N(float): ...
n: H = N()
[builtins fixtures/primitives.pyi]
1 change: 1 addition & 0 deletions test-data/unit/fixtures/primitives.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class int:
class float:
def __float__(self) -> float: pass
def __add__(self, x: float) -> float: pass
def hex(self) -> str: pass
class complex:
def __add__(self, x: complex) -> complex: pass
class bool(int): pass
Expand Down
Loading