Published June 09, 2025
Did you know that if you put a variable in a case statement it will assign the match value to it?
I didn't. That means that if you do this:
a = (None, 1)
match a:
case (int, _):
print(a[0])
case (_, int):
print(a[1])
case _:
print(-1)
you will end up with int is None.
The way to actually accomplish the intent of the above is to use int() instead of int
a = (None, 1)
match a:
case (int(), _):
print(a[0])
case (_, int()):
print(a[1])
case _:
print(-1)
So you can see what it looks like in the REPL:
>>> a = (None, 1)
>>> match a:
... case (int, _):
... print(a[0])
... case (_, int):
... print(a[1])
... case _:
... print(-1)
...
None
>>> print(int)
None
>>>a = (None, 1)
>>> match a:
... case (int(), _):
... print(a[0])
... case (_, int()):
... print(a[1])
... case _:
... print(-1)
...
1
>>> print(int)
<class 'int'>
As someone who likes using match statements I find this a bit disconcerting but, now that I
know about it I should be able to avoid running into this trap in the future.
Source: Python Discourse Forums.