Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
ai-py Avatar asked Oct 17 '25 19:10

ai-py


1 Answers

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.

like image 60
user2357112 supports Monica Avatar answered Oct 19 '25 08:10

user2357112 supports Monica