[Python] Optional matches in structural pattern matching

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a variable data incoming from a websocket and I'm using match/case to determine what to do with it. It's coming in as a tuple as below, but I want to match both of these the same.

    data = ("foo", )
    # or
    data = ("foo", {"bar": 213})


    Some cases I need the data, others I don't. In the case I don't need it (i.e. the case above where the first element is foo) I just want to essentially ignore the second variable if it's present.

    This is my current way of doing this but am I going about it wrong? Or is there a more succinct form?

    match data:
    case ["foo"] | ["foo", _]:
    ...
    case ["baz", x]:
    ...
    ...

    Continue reading...

Compartilhe esta Página