Skip to content

[match-case] class pattern narrowing with Union-argument different from equivalent isinstance call. #19468

Description

@randolf-scholz

case Cls() and isinstance(obj, Cls) should give the same narrowing behavior, but in the example below, the results differ when obj is a union-type.

class Foo: ...
class Bar(Foo): ...

def test_1(bar: Bar) -> None:
    match bar:
        case Foo() as foo:
            reveal_type(foo)  # N: Revealed type is "__main__.Bar"
            
def test_2(bar: Bar | str) -> None:
    match bar:
        case Foo() as foo:
            reveal_type(foo)  # N: Revealed type is "__main__.Foo"
            
def test_3(bar: Bar) -> None:
    if isinstance(bar, Foo):
        reveal_type(bar)  # N: Revealed type is "__main__.Bar"
            
def test_4(bar: Bar | str) -> None:
    if isinstance(bar, Foo):
        reveal_type(bar)  # N: Revealed type is "__main__.Bar"

https://mypy-play.net/?mypy=latest&python=3.12&gist=4bc28e67967c7809ccdd0962f3372dd7

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-match-statementPython 3.10's match statementtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions