You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅地将类属性用作类型注解?

基于RDF范式的对象ID建模

我采用和RDF相同的范式,将类及其非字面量属性建模为引用对象的ID(类似RDF中的URI),基础代码示例如下:

from typing import NewType

GUID = NewType("GUID", int)  # 创建int的子类

print(GUID.__name__) # 输出 'GUID'

class Person:
    id: GUID
    parents: list["PersonId"]
当前PersonId的定义方式

为了定义PersonId,我使用了以下代码:

import inspect
from typing import TypeAliasType, Annotated, Any

def field_info(class_model: type, attr_name: str) -> tuple[type, str, Any]:
    attributes = inspect.get_annotations(class_model)
    assert attr_name in attributes
    return (class_model, attr_name, attributes[attr_name])

PersonId = TypeAliasType("PersonId", Annotated[GUID, field_info(Person, "id")])  # 创建GUID的别名
序列化/反序列化时的校验逻辑

在数据库序列化/反序列化的代码中,我会做如下校验,确保注解类型和属性类型匹配(示例代码已简化,实际与Person类解耦):

from typing import get_origin, get_args

assert Person.__name__ == "Person"  # 结果为True
assert isinstance(PersonId, typing.TypeAliasType)  # 结果为True
origin = get_origin(PersonId.__value__)
args = get_args(PersonId.__value__)
assert origin is Annotated  # 结果为True
assert args[0] is GUID  # 结果为True
assert args[1] == (Person, "id", GUID)  # 结果为True
assert args[0] == args[1][2]  # 结果为True
疑问:能否简化PersonId的定义?

我想知道是否可以直接通过以下方式定义PersonId,但这样写会抛出AttributeError: type object 'Person' has no attribute 'id':

PersonId = TypeAliasType("PersonId", Person.id)

内容的提问来源于stack exchange,提问作者ticapix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 14:13:16