'How to do structural pattern matching in Python 3.10 with a type to match?
I am trying to match a type in Python 3.10 using the console:
t = 12.0
match type(t):
case int:
print("int")
case float:
print("float")
And I get this error:
File "<stdin>", line 2
SyntaxError: name capture 'int' makes remaining patterns unreachable
How can I fix this issue?
Solution 1:[1]
Loose the type()
and also add parentheses to your types:
t = 12.0
match t:
case int():
print("int")
case float():
print("float")
I'm not sure why what you've wrote is not working, but this one works.
Solution 2:[2]
My fix was:
match type(t):
case v if v is int:
print("int")
case v if v is float:
print("float")
It is not very elegant but it is the best I can do with pattern matching.
Solution 3:[3]
I think a more readable option instead of pattern matching is the following:
t = 12.0
if isinstance(t, int):
print("int")
elif isinstance(t, float):
print("float")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mmohaveri |
Solution 2 | Pierre Thibault |
Solution 3 |