【问题标题】:Type annotations for dynamically created subclasses动态创建子类的类型注解
【发布时间】:2021-09-29 22:09:41
【问题描述】:

我想在启动时使用type() 函数动态创建子类。一切都按预期工作。 我知道这不是很好,但我受制于一个框架并且必须这样做。另一种选择是生成源代码...

功能等同于我的代码:

class BaseEntity:
    id: str


def make_new_entity(name: str, attrs: dict) -> type:
    return type('RuntimeEntity', (BaseEntity,), attrs)


RuntimeEntity: ??? = make_new_entity('RuntimeEntity', {'id': 'entity.RuntimeEntity'})

有没有办法为返回的类型提供绑定?基本上相当于

E = TypeVar('E', bound='BaseEntity')

我还查看了types 模块。

感谢您的帮助!

【问题讨论】:

    标签: python dynamic types typing


    【解决方案1】:

    typing.Type 允许您指定值应该是实际类型,而不是该类型的实例。

    from typing import Type
    
    class BaseEntity:
        id: str
    
    
    def make_new_entity(name: str, attrs: dict) -> Type[BaseEntity]:
        return type('RuntimeEntity', (BaseEntity,), attrs)
    
    
    RuntimeEntity: Type[BaseEntity] = make_new_entity('RuntimeEntity', {'id':     'entity.RuntimeEntity'})
    

    Type[BaseEntity] 类型的值可以是BaseEntity 本身,也可以是从BaseEntity 继承的任何类。 (描述这一点的术语是协方差。如果Type不变的Type[BaseEntity] 将只接受BaseEntity 本身。)

    【讨论】:

    • 太好了,谢谢!我试过了,但是因为 PyCharm 说“预期类型 'Type[BaseEntity]',得到了 'type' 而不是”而感到困惑。 IntelliSense 虽然适用于实例。可能是一个错误或无法 lint。
    • 在我输入的字典中更糟糕的是:“预期类型Dict[str, Type[BaseEntity]],得到Dict[str, type]
    • 在显示的代码中mypy 没有出现任何错误。
    猜你喜欢
    • 2018-06-20
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多