简体   繁体   English

如何用结构模式匹配表达 hasattr() 鸭子类型逻辑?

[英]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 的匹配/大小写结构模式匹配来表达这一点?

Understanding the documentation了解文档

PEP 634 for structural pattern matching documents this capability as a class pattern :用于结构模式匹配的PEP 634将此功能记录为class 模式

  • Writing cls() will do an isinstance() test.编写cls()将执行isinstance()测试。
  • Adding a keyword pattern 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()

  • Set cls to object so that any class can match.cls设置为object以便任何 class 都可以匹配。
  • Set attr to _fields , the attribute that must be present.attr设置为_fields ,这是必须存在的属性。
  • Set variable to _ if you don't need to capture the value or to some other variable name if you do want to capture the value.如果您不需要捕获该值,请将变量设置为_ ,如果您确实想捕获该值,请将其设置为其他变量名。

This specific example这个具体的例子

Your specific example, if hasattr(candidate, '_fields'): do_action() , translates to:您的具体示例, if hasattr(candidate, '_fields'): do_action() ,转换为:

match candidate:
   case object(_fields=_):
       do_action()

Complete worked-out example完整的计算示例

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.

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