Skip to content

Type Narrowing: if val == Literal should always narrow to Literal #16819

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

Open
CarliJoy opened this issue Jan 25, 2024 · 3 comments
Open

Type Narrowing: if val == Literal should always narrow to Literal #16819

CarliJoy opened this issue Jan 25, 2024 · 3 comments
Labels

Comments

@CarliJoy
Copy link

Feature

Currently mypy already type narrows literals in if

def works(abc: Literal["a", "b", "c"]):
    a: Literal["a"] | None = None
    if abc == "a":
        a = abc

def works_not(anystring: str):
    a: Literal["a"] | None = None
    if anystring == "a":
        a = anystring  # expression has type str

More Complete MyPy Play

Pitch

See #16813 for an example why this is useful.
In general working with TypedDicts in for loop this helps a lot reducing duplicate code / keys.

@JelleZijlstra
Copy link
Member

Agree. There's some risk this could lead to new false positives in cases involving invariance, but on balance this is almost certainly a positive.

@erictraut
Copy link

FWIW, pyright applies narrowing in this case. Pyright playground. I haven't observed false positives in cases involving invariance, but I agree that could be a small concern if code bases are relying on mypy's current behavior.

@CarliJoy
Copy link
Author

Actually the full example works already in pyright as expected

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

No branches or pull requests

3 participants