python - 动态泛型类生成
问题描述
我正在尝试键入一个动态创建的通用类,以便将对另一个对象的引用放入类变量中。
但是,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]'
有什么线索吗?
解决方案
推荐阅读
- javascript - javascript: 因子 if 语句
- algorithm - O(n) 中加权树中的最大匹配
- php - 是否有一些简单的方法可以从表单(php)编辑最后一行数据
- azure - 在支持多个环境时,使用 Azure AD 的正确方法是什么?
- python - 如何在 Scikit-learn RandomForest 中获得训练精度?
- javascript - console.log 二叉树中的节点,其子树的总和为偶数
- angular - 将数据从一个函数分配给另一个函数
- c# - Xenforo 登录系统
- java - 使用 ANTLR 解析 Java 表达式
- ruby-on-rails - 从 Active Admin 的所有页面中删除 :destroy