Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match with int() and bool()

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)
like image 494
Pierre Lepage Avatar asked Oct 27 '25 07:10

Pierre Lepage


1 Answers

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
like image 152
trincot Avatar answered Oct 28 '25 21:10

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!