Fix checking of match sequence pattern against bounded type variables by brianschubert · Pull Request #18091 · python/mypy (original) (raw)

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 andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Conversation4 Commits1 Checks18 Files changed

Conversation

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters

[ Show hidden characters]({{ revealButtonHref }})

brianschubert

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]"

@brianschubert

@github-actions GitHub Actions

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

hauntsaninja

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

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:

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.

@JukkaL

Changing less now might make that a bit easier.

Ok, let's merge this as is.