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

Narrow down right hand-side of an == expression in ifs #9093

Closed
elenakrittik opened this issue Sep 26, 2024 · 2 comments
Closed

Narrow down right hand-side of an == expression in ifs #9093

elenakrittik opened this issue Sep 26, 2024 · 2 comments
Labels
enhancement request New feature or request

Comments

@elenakrittik
Copy link

Is your feature request related to a problem? Please describe.

if a == 1 narrows a to Literal[1], but if 1 == a does not

playground

Describe the solution you’d like

Narrow down the type of a in both cases

@elenakrittik elenakrittik added the enhancement request New feature or request label Sep 26, 2024
@erictraut
Copy link
Collaborator

Yes, this is intended behavior. Pyright supports the x == L and x != L type guard patterns for type narrowing, but it doesn't support the converse, which is not a typical usage pattern in Python.

For a full list of supported type guard patterns, refer to this documentation.

We do occasionally add support for new patterns, but each one requires special-case logic and has the potential for slowing down overall type analysis, so we do so only in cases where we have strong signal from pyright users that it's a common pattern. Adding this case would likely slow down code flow analysis in a measurable way, especially for complex functions in untyped code. This is important when inferring return types for untyped library functions, especially in scientific libraries, so I don't think it would be a good tradeoff for pyright users to add support for this type guard pattern.

I've rarely seen L == x used in code, and it's trivial to change this to the more common x == L pattern.

For those reasons, I'm going to reject this enhancement request for now. I'm willing to revisit the decision if there's sufficient interest from pyright users.

@erictraut erictraut closed this as not planned Won't fix, can't repro, duplicate, stale Sep 26, 2024
@elenakrittik
Copy link
Author

Thank you for the explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement request New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants