Skip to content

Inconsistent Behavior of match-case Statement with Dict Literals {} and dict() Constructor #106133

@abyesilyurt

Description

@abyesilyurt

Bug report

The behavior of the match-case statement seems to be inconsistent when using dictionary literals {} and dict() constructor in the case clause.

def match_test(data_dict):
    match data_dict:
        case {"name": name, "entries": [{"id": id}]}:
            print("1st match stmt., 1st case")
        case dict(name=name, entries=[dict(id=id)]):
            print("1st match stmt., 2nd case")

    match data_dict:
        case dict(name=name, entries=[dict(id=id)]):
            print("2nd match stmt., 1st case")
        case {"name": name, "entries": [{"id": id}]}:
            print("2nd match stmt., 2nd case")

data_dict_1 = {"name": "test", "entries": [{"id": "test"}]}
data_dict_2 = dict(name="test", entries=[dict(id="test")])

match_test(data_dict_1)
match_test(data_dict_2)

Output

1st match stmt., 1st case
2nd match stmt., 2nd case
1st match stmt., 1st case
2nd match stmt., 2nd case

This suggests that the match-case statement first matches with the pattern that is defined using the same syntax ({} or dict()) as the input dictionary, regardless of the pattern order in the case clauses.

Expected Output

I would expect that the first statement would be matched in this case, regardless of how the dict is initialized.

1st match stmt., 1st case
2nd match stmt., 1nd case
1st match stmt., 1st case
2nd match stmt., 1nd case

Your environment

Python 3.10.12 | packaged by conda-forge | (main, Jun 23 2023, 22:41:52) [Clang 15.0.7 ] on darwin

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions