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

Type narrowing with isinstance() doesn't work correctly for Union types #8302

Open
wch opened this issue Jul 3, 2024 · 2 comments
Open

Type narrowing with isinstance() doesn't work correctly for Union types #8302

wch opened this issue Jul 3, 2024 · 2 comments
Labels
addressed in next version Issue is fixed and will appear in next published version bug Something isn't working

Comments

@wch
Copy link

wch commented Jul 3, 2024

Consider this code.

Foo = int | str


def f(x: Foo | list[Foo]) -> None:
    if isinstance(x, Foo):
        x = [x]

    [y for y in x]

With pyright 1.1.370, this results in an error:

❯ pyright test.py
/Users/winston/py-shiny/test.py
  /Users/winston/test.py:6:14 - error: Expression of type "list[Foo | list[Foo]]" is incompatible with declared type "Foo | list[Foo]" (reportAssignmentType)
  /Users/winston/test.py:8:12 - error: Type of "y" is unknown (reportUnknownVariableType)
  /Users/winston/test.py:8:17 - error: "int" is not iterable
    "__iter__" method not defined (reportGeneralTypeIssues)
3 errors, 0 warnings, 0 informations

It looks like inside of the if isinstance(x, Foo): block, it is not narrowing x to Foo; it still thinks it could be Foo | list[Foo].

If I change the definition of Foo so that it's just Foo = int (and not a union type) then no error is reported.

@wch wch added the bug Something isn't working label Jul 3, 2024
@erictraut
Copy link
Collaborator

I'm not seeing any errors for the above code snippet. Did you mean for Foo = int to be Foo = int | str or something like that?

@wch
Copy link
Author

wch commented Jul 3, 2024

Sorry, I did mean Foo = int | str! I have corrected the example.

erictraut added a commit that referenced this issue Jul 3, 2024
…type alias (not using PEP 695 syntax) defines a union and is then used as a second argument to an `isinstance` or `issubclass` call. This addresses #8302.
erictraut added a commit that referenced this issue Jul 3, 2024
…type alias (not using PEP 695 syntax) defines a union and is then used as a second argument to an `isinstance` or `issubclass` call. This addresses #8302. (#8303)
@erictraut erictraut added the addressed in next version Issue is fixed and will appear in next published version label Jul 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
addressed in next version Issue is fixed and will appear in next published version bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants