KEMBAR78
Enable negative narrowing of Union TypeVar upper bounds by brianschubert · Pull Request #17850 · python/mypy · GitHub
Skip to content

Conversation

brianschubert
Copy link
Member

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
Member 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

@github-actions
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