Skip to content

Enable negative narrowing of Union TypeVar upper bounds - #17850

Merged
hauntsaninja merged 2 commits into
python:masterfrom
brianschubert:gh-15235-enable-narrowing-typevar-bound
Sep 30, 2024
Merged

hauntsaninja merged 2 commits into
python:masterfrom
brianschubert:gh-15235-enable-narrowing-typevar-bound

Conversation

@brianschubert

Copy link
Copy Markdown
Collaborator

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

brianschubert commented Sep 29, 2024 •

Copy link
Copy Markdown
Collaborator Author

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

@github-actions

Copy link
Copy Markdown
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]

@hauntsaninja hauntsaninja left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks!

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