繁体   English   中英

将多个 isinstance 检查转换为结构模式匹配

[英]Convert multiple isinstance checks to structural pattern matching

我想将此现有代码转换为使用模式匹配:

if isinstance(x, int):
    pass
elif isinstance(x, str):
    x = int(x)
elif isinstance(x, (float, Decimal)):
    x = round(x)
else:
    raise TypeError('Unsupported type')

您如何编写带有模式匹配的isinstance检查,以及如何同时针对多种可能的类型进行测试,例如(float, Decimal)

转换为模式匹配的示例

这是使用matchcase的等效代码:

match x:
    case int():
        pass
    case str():
        x = int(x)
    case float() | Decimal():
        x = round(x)
    case _:
        raise TypeError('Unsupported type')

解释

PEP 634指定使用class 模式执行isinstance()检查。 要检查str的实例,请编写case str(): ... 请注意,括号是必不可少的。 这就是语法如何确定这是一个 class 模式。

为了一次检查多个类,PEP 634 提供了一个使用|或模式 操作员。 例如,要检查 object 是否是floatDecimal的实例,请编写case float() | Decimal(): ... case float() | Decimal(): ... 和以前一样,括号是必不可少的。

使用 python match case

无异常处理

match x:
    case int():
        pass
    case str():
        x = int(x)
    case float() | Decimal():
        x = round(x)
    case _:
        raise TypeError('Unsupported type')

一些额外的东西

这段代码中仍有一些流程。

带异常处理

match x:
    case int():
        pass
    case str():
        try:
            x = int(x)
        except ValueError:
            raise TypeError('Unsupported type')
    case float() | Decimal():
        x = round(x)
    case _:
        raise TypeError('Unsupported type')

作为 function

def func(x):
    match x:
        case int():
            pass
        case str():
            try:
                x = int(x)
            except ValueError:
                raise TypeError('Unsupported type')
        case float() | Decimal():
            x = round(x)
        case _:
            raise TypeError('Unsupported type')
    return x

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM