[Potential Bug] Type-narrowing based on x in y
#9337
-
I'm asking if the current behavior is intentional, because it looks much like a bug to me. We can now have following snippet pass type-checking - from typing_extensions import assert_type
def foo(x: float = 0.0, y: list[int] = [0]):
if x in y:
_ = assert_type(x, "int") # !!! The type-narrowing of On the other hand, type-narrowing based on from typing_extensions import Literal, assert_type
def foo(x0: float = 0.0, x1: int = 0, L: Literal[0] = 0):
if x0 == L:
assert_type(x0, "float") # No type-narrowing.
if x1 == L:
assert_type(x1, "Literal[0]") # Safe. My suggestion is that type-narrowing based of My expected behavior would be like following examples - from typing_extensions import Literal, assert_type
def f0(x: int, y: list[Literal[0, 1]]):
if x in y:
_ = assert_type(x, "Literal[0, 1]") # Narrowed.
def f1(x: Literal[-1, 0], y: list[Literal[0, 1]]):
if x in y:
_ = assert_type(x, "Literal[0]") # Narrowed.
def f2(x: Literal[0, 1, 2], y: list[Literal[0, 1]]):
if x in y:
_ = assert_type(x, "Literal[0, 1]") # Narrowed.
def f3(x: float, y: list[int]):
if x in y:
_ = assert_type(x, "float") # Not narrowed, because `int` is not a literal type or a union of literal types.
def f4(x: float, y: list[Literal[0, 1]]):
if x in y:
_ = assert_type(x, "float") # Not narrowed, because `float` is not `int`.
def f5(x: int, y: list[Literal[0, True]]):
if x in y:
_ = assert_type(x, "int") # Not narrowed, because `Literal[0]` and `Literal[True]` don't share a same runtime type.
def f6(x: bool, y: list[Literal[0, 1]]):
if x in y: # Assuming this is allowed.
_ = assert_type(x, "bool") # Not narrowed, because `bool` is not `int`. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I agree this is a bug. Thanks for reporting it. I'm surprised no one has reported this previously since it has existed for more than two years. Converting to an issue so it is tracked. |
Beta Was this translation helpful? Give feedback.
I agree this is a bug. Thanks for reporting it. I'm surprised no one has reported this previously since it has existed for more than two years.
Converting to an issue so it is tracked.