首页 > 解决方案 > 动态泛型类生成

问题描述

我正在尝试键入一个动态创建的通用类,以便将对另一个对象的引用放入类变量中。

但是,mypy 返回的类型与构造函数中使用的推断值不匹配。

这是一个简单的例子:

from typing import Any,  ClassVar, Generic, Type, TypeVar


T = TypeVar("T")
class Item(Generic[T]):
    _REGISTRY: ClassVar[Any]

    def __new__(cls, value: T) -> "Item[T]":
        instance = super(Item, cls).__new__(cls)
        instance._value = value
        return instance

def build_item(registry: Any) -> Type[Item]:

    class DynamicItem(Item):
        _REGISTRY = registry

    return DynamicItem

ItemType = build_item("dynamic_class_var")
item_static = Item(0.1)
item_dynamic = ItemType(0.1)

reveal_type(item_static)
reveal_type(item_dynamic)

我得到以下运行 mypy :


note: Revealed type is 'item.Item[builtins.float*]'
note: Revealed type is 'item.Item[Any]'

有什么线索吗?

标签: pythonmypypython-typing

解决方案


推荐阅读