Search code examples
pythonpython-3.10structural-pattern-matching

Why is underscore not a valid name in new Python match?


_ score can be used as a variable name anywhere in Python, such as:

_ = 10
print(_)

However, it is not accepted here:

d = dict(john = 10, owen=12, jenny=13)
match d:
    case {'john' : 10, 'jenny': _}:
        print('does not work', _)
ERROR: print('does not work', _)
NameError: name '_' is not defined

Yet, perfectly fine to use as follows:

d = dict(john = 10, owen=12, jenny=13)
match d:
    case {'john' : 10, 'jenny': a}:
        print('does not work', a)

Why is _ not a valid variable name in new match in Python 3.10?


Solution

  • In a match statement, _ is a wildcard pattern. It matches anything without binding any names, so you can use it multiple times in the same case without having to come up with a bunch of different names for multiple values you don't care about.