Skip to content

Cannot use match case to destructure any object using case object(x=y) #16912

@RenDelaCruz

Description

@RenDelaCruz

Bug Report

In the global scope, mypy allows destructuring any object in match case with object(x=y):

@dataclass
class A:
    id: int

# SUCCESS
match A(id=5):
    case object(id=object_id):
        print(object_id)

However, in a method, mypy errors out trying to use object(x=y) in match case:

# FAILURE
def get_id_from_any_object(obj: object) -> int | None:
    match obj:
        # main.py:19: error: Class "builtins.object" has no attribute "id"
        case object(id=object_id):
            return object_id
        case _:
            return None

Edit: Turns out, it is not due to scoping, but due to the type of the match <subject>. See #16912 (comment)

To Reproduce

mypy playground:
https://mypy-play.net/?mypy=latest&python=3.12&gist=c5799b1b128c52894f2879f9fc8d0115

Expected Behavior

Should allow using case object(x=y) in match case syntax.

Actual Behavior

Errors out trying case object(x=y) in match case syntax, inside a method. Does not error out in global scope.

Your Environment

  • Mypy version used: 1.8.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

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