I came across a weird issue while using the new match
/case
syntax in Python3.10. The following example seems like it should work, but throws an error:
values = [
1,
"hello",
True
]
for v in values:
match type(v):
case str:
print("It is a string!")
case int:
print("It is an integer!")
case bool:
print("It is a boolean!")
case _:
print(f"It is a {type(v)}!")
$ python example.py
File "/.../example.py", line 9
case str:
^^^
SyntaxError: name capture 'str' makes remaining patterns unreachable
- It is mentioning that the first case (the value
str
) will always result inTrue
.
Wondering if there is an alternative to this other than converting the type to a string.
case
is followed by a pattern. Identifiers in patterns are variables that will be assigned from the corresponding part of the matching value, not they're not variables that are evaluated.case str:
means that if the value is a single value, assign the value tostr
and execute that case body. It doesn't meanif type(v) == str:
switch/case
from PHP or JavaScript.