Today I learned that the underscore _
is a soft keyword in Python.
I've written about the multiple usages of the underscore _
in Python and in that article I write about the fact that the underscore is idiomatically used to assign a value we don't care about.
Something like this:
# Suppose we have a colour like `colour = ("red", (255, 0, 0))`
colour_name, _ = colour
The code above uses unpacking to extract the colour name from the variable colour
and we use the second variable name _
to idiomatically say “we expect there to be a second value to unpack, but we don't care about its value”.
But this is just a convention.
There is nothing special about the underscore _
in this situation; it's just a valid variable name:
_ = 3
_ *= 2
print(_) # 6
However, in Python's 3.10 match
statement, the underscore _
was turned into a soft keyword.
This means that when you write a match
statement containing a case
statement that looks like case _:
, Python actually parses the underscore _
as a keyword!
So, if _
can be used as a regular variable name and if _
can be parsed as a keyword, depending on the context, that makes it a soft keyword!
To confirm that _
can be parsed as a keyword inside a case
statement, don't take my word for it.
You can open Python's grammar and see for yourself!
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book “Pydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here 🐍🚀.