[Python] Why does Python's Structural Pattern Matching not support multiple assignment?

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    I was experimenting with Python Structural Pattern Matching and wanted to write a match statement capable of matching repeated occurrences in a sequence.

    Suppose that I have the following list of tuples and was trying to match every pair in which the first element of the tuple is the same.

    from itertools import combinations

    objs = (('a', 'b'), ('c', 'd', 'e'), ('f',), ('a', 'g'), ('b', 'a'))
    pairs = list(combinations(objs, 2))


    The goal was my code to match the pair: (('a', 'b'), ('a', 'g')) as both tuples starts with 'a'.

    My first attempt was:

    from itertools import combinations

    objs = (('a', 'b'), ('c', 'd', 'e'), ('f',), ('a', 'g'), ('b', 'a'))
    pairs = list(combinations(objs, 2))

    for pair in pairs:
    match pair:
    # This raises Syntax Error!
    case ((x, *y), (x, *z)): print('Found!')
    case _: pass


    However this raises: SyntaxError: multiple assignments to name 'x' in pattern.

    A possible work around I guess is to use guards in which one gives different names such as x1 and x2 and then matches only if x1 == x2, however this can quickly become quite messy if I want to enforce more than one equality. In my opinion using the same binding name is both elegant and practical with the obvious implication that the two should be the same.

    And so I ask, is there any reason why Structural Pattern Matching enforces the variable names to be different? Is there a nicer way to accomplish this that I'm missing?

    Continue reading...

Compartilhe esta Página