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

Fix checking of match sequence pattern against bounded type variables #18091

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

brianschubert
Copy link
Collaborator

Fixes #18089

Adds handling for bounded type variables when checking match sequence patterns.

Previously, this crashed. Now, this correctly narrows the upper bound of the type variable:

from typing import TypeVar, Sequence

T = TypeVar("T", bound=Sequence[int | str])

def accept_seq_int(x: Sequence[int]): pass

def f(x: T) -> None:
    match x:
        case [1, 2]:
            accept_seq_int(x)  # ok: upper bound narrowed to Sequence[int]
        case _:
            accept_seq_int(x)  # E: Argument 1 to "accept_seq_int" has incompatible type "T"; expected "Sequence[int]"

Copy link
Contributor

github-actions bot commented Nov 2, 2024

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

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! Would it make sense to move logic into construct_sequence_child?

@brianschubert
Copy link
Collaborator Author

Hmm, it probably would, though I'm hesitant to touch construct_sequence_child directly since it looks like it might need some more careful refactoring in the future to fix this TODO in its docstring:

mypy/mypy/checkpattern.py

Lines 750 to 751 in 1f200dd

TODO: this doesn't make sense. For example if one has class S(Sequence[int], Generic[T])
or class T(Sequence[Tuple[T, T]]), there is no way any of those can map to Sequence[str].

Changing less now might make that a bit easier.

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.

Crash on sequence match statement in generic class with restricted type variable bound to sequence
2 participants