Home > Mobile >  Optional matches in structural pattern matching
Optional matches in structural pattern matching

Time:06-03

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]:
            ...
        ...

CodePudding user response:

As usual with star unpacking, variable (or underscore) with a star matches zero or more items. So the following will work:

data = ['foo']

match data:
    case ['foo', *_]:
        print('Matched')

It is similar to common iterable unpacking:

a, *b = [1]
assert a == 1
assert b == []

Note: it is different from your original code, because ['foo', {}, {}] will be matched too. There is no analogue of regex ? quantifier, so "no more than one" cannot be expressed this way.

  • Related