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

Add regression test cases #17869

Merged
merged 1 commit into from
Oct 5, 2024
Merged
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
42 changes: 42 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -2206,3 +2206,45 @@ def f3(x: object) -> None:
else:
reveal_type(x) # N: Revealed type is "builtins.object"
[builtins fixtures/primitives.pyi]

[case testConsistentNarrowingEqAndIn]
# flags: --python-version 3.10

# https://github.com/python/mypy/issues/17864
def f(x: str | int) -> None:
if x == "x":
reveal_type(x) # N: Revealed type is "Union[builtins.str, builtins.int]"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this desired behavior? I feel like we should narrow to Literal["x"]. Yes, it might be a subclass of int that compares equal with str, but don't do that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this case seems fine. But classes that compare equal to int are not unusual (e.g. Decimal), so it's not clear where to draw the line. We might need some ad-hoc rules to support common use cases.

Copy link
Collaborator Author

@hauntsaninja hauntsaninja Oct 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The last time I tried that change IIRC it looked pretty good on primer, I think the main obstacle was it exposed some shortcomings in the binder

y = x

if x in ["x"]:
# TODO: we should fix this reveal https://github.com/python/mypy/issues/3229
reveal_type(x) # N: Revealed type is "Union[builtins.str, builtins.int]"
y = x
z = x
z = y
[builtins fixtures/primitives.pyi]

[case testConsistentNarrowingInWithCustomEq]
# flags: --python-version 3.10

# https://github.com/python/mypy/issues/17864
class C:
def __init__(self, x: int) -> None:
self.x = x

def __eq__(self, other: object) -> bool:
raise
# Example implementation:
# if isinstance(other, C) and other.x == self.x:
# return True
# return NotImplemented

class D(C):
pass

def f(x: C) -> None:
if x in [D(5)]:
reveal_type(x) # D # N: Revealed type is "__main__.C"

f(C(5))
[builtins fixtures/primitives.pyi]
Loading