[英]How to express hasattr() duck typing logic with structural pattern matching?
I have code that checks for named tuples and dataclasses by looking for a _fields
attribute:我有通过查找_fields属性来检查命名元组和数据类的
_fields
:
if hasattr(candidate, '_fields'):
do_action()
How can I express this with Python 3.10's match/case structural pattern matching?如何使用 Python 3.10 的匹配/大小写结构模式匹配来表达这一点?
PEP 634 for structural pattern matching documents this capability as a class pattern :用于结构模式匹配的PEP 634将此功能记录为class 模式:
cls()
will do an isinstance() test.cls()
将执行isinstance()测试。cls(attr=variable)
tests for the presence of an attribute and binds the value to the variable.cls(attr=variable)
测试属性是否存在并将值绑定到变量。 To emulate a hasattr() for duck typing :要模拟鸭子类型的hasattr() :
_fields
, the attribute that must be present._fields
,这是必须存在的属性。_
if you don't need to capture the value or to some other variable name if you do want to capture the value._
,如果您确实想捕获该值,请将其设置为其他变量名。Your specific example, if hasattr(candidate, '_fields'): do_action()
, translates to:您的具体示例,
if hasattr(candidate, '_fields'): do_action()
,转换为:
match candidate:
case object(_fields=_):
do_action()
This shows how all the parts fit together:这显示了所有部分如何组合在一起:
from typing import NamedTuple
from dataclasses import dataclass
class Whale(NamedTuple):
name: str
num_fins: int
@dataclass
class Vehicle:
name: str
num_wheels: int
subject = Vehicle('bicycle', 2)
match subject:
case object(num_fins=n):
print(f'Found {n} fins')
case object(num_wheels=_):
print(f'Found wheeled object')
case _:
print('Unknown')
This script outputs:该脚本输出:
Found wheeled object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.