Skip to content

Can't infer tuple inside match case #18039

Open
@racinmat

Description

@racinmat

Bug Report

(A clear and concise description of what the bug is.)

To Reproduce

from typing import Any, Union

Sentence = Union[str, tuple[str, str]]
Sample = Union[Sentence, bytes, bytearray, dict[str, Any]]

def instance2sentence(i: Sample) -> Sentence:
    match i:
        case {"text": j}:
            return instance2sentence(j)
        case [str(), str()]:
            return tuple(i) # this fails
        case str():
            return i
        case _:
            raise AssertionError(f"Unsupported instance type")


instance2sentence("sentence1")
instance2sentence(("sentence1", "label1"))
instance2sentence({"text": "text sample 3"})

Expected Behavior

The code should pass, because the pattern matching makes sure the tuple(i) is only tuple[str, str].

Actual Behavior

main.py:11: error: Incompatible return value type (got "tuple[object, ...]", expected "str | tuple[str, str]")  [return-value]

Your Environment

Mypy playground: https://mypy-play.net/?mypy=latest&python=3.13&gist=e3671ab907e180d0cc6b60aefeec2052

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-match-statementPython 3.10's match statement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions