With Python 3.10.2, consider this code snippet.
def print_type(v):
match v:
case int() as v:
s = f"int {v}"
case bool() as v:
s = f"bool {v}"
case _:
s = "other"
print(s)
Try it with 's = False' and it will print 'bool False' as expected. Now reverse the bool() and int() cases and the result will now be 'int False'. Not exactly what I expected.
Is it a bug? If so, I'll post on the Python forum.
EDIT
Based on trincot's answer, here is a version of the code that has the expected behavior.
def print_type(v):
match v:
case int() as v:
if isinstance(v, bool):
s = f"bool {v}"
else:
s = f"int {v}"
case _:
s = "other"
print(s)
No, this is not a bug. bool is a subclass of int, and so every boolean is also an integer.
print(isinstance(True, int)) # True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With