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

Enable negative narrowing of Union TypeVar upper bounds #17850

Conversation

brianschubert
Copy link
Contributor

Fixes #15235

Before

from typing import TypeVar

class A:
    pass
class B:
    b: int

T = TypeVar("T", bound=A | B)


def foo(x: T) -> T:
    if isinstance(x, A):
        reveal_type(x)      # N: Revealed type is "__main__.A"
    else:
        reveal_type(x)      # N: Revealed type is "T`-1"
        x.b                 # E: Item "A" of the upper bound "A | B" of type variable "T" has no attribute "b"
    return x

After

from typing import TypeVar

class A:
    pass
class B:
    b: int

T = TypeVar("T", bound=A | B)


def foo(x: T) -> T:
    if isinstance(x, A):
        reveal_type(x)      # N: Revealed type is "__main__.A"
    else:
        reveal_type(x)      # N: Revealed type is "T`-1"
        x.b                 # ok! Upper bound of T narrowed to B
    return x

Better fit for 'check-isinstance.test'

New test 'testNarrowingTypeVarConstraints' is already covered by
'testIsInstanceAdHocIntersectionGenericsWithValues'
@brianschubert
Copy link
Contributor Author

brianschubert commented Sep 29, 2024

I believe this is consistent with the way pyright applies negative narrowing to TypeVars with union upper bounds: Pyright playground

Copy link
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

artigraph (https://github.com/artigraph/artigraph)
- src/arti/internal/type_hints.py:177: error: Argument 2 to "_check_issubclass" has incompatible type "T"; expected "type"  [arg-type]

Copy link
Collaborator

@hauntsaninja hauntsaninja left a comment

Choose a reason for hiding this comment

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

Thanks!

@hauntsaninja hauntsaninja merged commit 7dc23fe into python:master Sep 30, 2024
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

False-positive due to missing type narrowing in isinstance of TypeVar
2 participants