[英]Convert multiple isinstance checks to structural pattern matching
I want to convert this existing code to use 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')
How do you write isinstance
checks with pattern matching, and how do you test against multiple possible types like (float, Decimal)
at the same time?您如何编写带有模式匹配的
isinstance
检查,以及如何同时针对多种可能的类型进行测试,例如(float, Decimal)
?
Here's the equivalent code using match and case :这是使用match和case的等效代码:
match x:
case int():
pass
case str():
x = int(x)
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
PEP 634 specifies that isinstance() checks are performed with class patterns . PEP 634指定使用class 模式执行isinstance()检查。 To check for an instance of str , write
case str(): ...
.要检查str的实例,请编写
case str(): ...
。 Note that the parentheses are essential.请注意,括号是必不可少的。 That is how the grammar determines that this is a class pattern.
这就是语法如何确定这是一个 class 模式。
To check multiple classes at a time, PEP 634 provides an or-pattern using the |
为了一次检查多个类,PEP 634 提供了一个使用
|
的或模式。 operator.操作员。 For example, to check whether an object is an instance of float or Decimal , write
case float() | Decimal(): ...
例如,要检查 object 是否是float或Decimal的实例,请编写
case float() | Decimal(): ...
case float() | Decimal(): ...
. case float() | Decimal(): ...
。 As before, the parentheses are essential.和以前一样,括号是必不可少的。
Using python match
case
使用 python
match
case
Without Exception handling无异常处理
match x:
case int():
pass
case str():
x = int(x)
case float() | Decimal():
x = round(x)
case _:
raise TypeError('Unsupported type')
Some extras一些额外的东西
There are still some flows in this code.这段代码中仍有一些流程。
With exception handling带异常处理
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')
As a function作为 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.