匹配 int() 和 bool()

match with int() and bool()

使用 Python 3.10.2,考虑这个代码片段。

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)

用 's = False' 试试,它会按预期打印 'bool False'。现在反转 bool() 和 int() 的情况,结果现在是 'int False'。不完全是我的预期。

这是一个错误吗?如果是这样,我会 post 在 Python 论坛上。

编辑

根据 trincot 的回答,这是具有预期行为的代码版本。

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)

不,这不是错误。 boolint 的子类,因此每个布尔值也是整数。

print(isinstance(True, int))  # True