3

_ 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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ai-py
  • 177
  • 1
  • 7

1 Answers1

4

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505