为什么 Python 匹配列表作为元组?

Why Python matches a list as a tuple?

使用Python 3.11.0a2+,以及以下代码:

def my_fun(e):
    match e:
        case (1,):
            print("tuple (1,)")
        case [1]:
            print("list [1]")
        case _:
            print("I don't understand")

使用 my_fun([1]) 调用函数打印“元组 (1,)”。

这种行为是否正确?

如果我明确匹配 tuple((1, )) 而不是 (1,),它将按预期工作。

如果这不是解释器的错误,那么这种看似奇怪的行为背后的原因是什么?

这是documented under Structural Pattern Matching

Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. Technically, the subject must be a sequence. Therefore, an important exception is that patterns don’t match iterators. Also, to prevent a common mistake, sequence patterns don’t match strings.

并在 PEP 635 -- Structural Pattern Matching: Motivation and Rationale

As in iterable unpacking, we do not distinguish between 'tuple' and 'list' notation. [a, b, c], (a, b, c) and a, b, c are all equivalent. While this means we have a redundant notation and checking specifically for lists or tuples requires more effort (e.g. case list([a, b, c])), we mimic iterable unpacking as much as possible.