gpt4 book ai didi

带有协议(protocol)和 TypeVar 的 Python 类型提示以指定任意数据类

转载 作者:行者123 更新时间:2023-12-04 13:33:07 25 4
gpt4 key购买 nike

我正在编写一个可以在内存中存储任意数据类的类。在那里我试图指定要存储的实例必须是数据类并且具有 id field 。此外,应该可以通过指定类和实例的 id 来获取实例。
我正在努力定义正确的类型提示。我已经想通了,我(可能)需要 TypeVar 的组合和 Protocol .这是我当前的代码:

import typing
import uuid
from collections import defaultdict
from dataclasses import field, dataclass


class DataclassWithId(typing.Protocol):
__dataclass_fields__: typing.Dict
id: str


Klass = typing.TypeVar("Klass", bound=DataclassWithId)


class InMemoryDataClassStore:
def __init__(self):
self._data_store = defaultdict(lambda: dict())

def add(self, instance: Klass):
store_for_class = self._get_store_for_class(instance.__class__)
store_for_class[instance.id] = instance

def get(self, klass: typing.Type[Klass], id_: str) -> Klass:
return self._get_store_for_class(klass)[id_]

def get_all(self, klass) -> typing.List[Klass]:
return list(self._get_store_for_class(klass).values())

def _get_store_for_class(
self, klass: typing.Type[Klass]
) -> typing.Dict[str, Klass]:
return self._data_store[klass]


auto_uuid_field = field(default_factory=lambda: str(uuid.uuid4()))

@dataclass
class ClassA:
name: str
id: str = auto_uuid_field


store = InMemoryDataClassStore()
instance_a = ClassA(name="foo")
store.add(instance_a)
print(store.get(klass=ClassA, id_=instance_a.id).name)
print(store.get(klass=ClassA, id_=instance_a.id).other_name) # supposed to cause a typing error

如果我跑 mypy针对这个文件,我得到
in_memory_data_store.py:45: error: Value of type variable "Klass" of "add" of "InMemoryDataClassStore" cannot be "ClassA"
in_memory_data_store.py:46: error: Value of type variable "Klass" of "get" of "InMemoryDataClassStore" cannot be "ClassA"
in_memory_data_store.py:47: error: Value of type variable "Klass" of "get" of "InMemoryDataClassStore" cannot be "ClassA"
in_memory_data_store.py:47: error: "ClassA" has no attribute "other_name" # expected
请有人帮助我了解类型提示吗?
最好的事物
拉斯

最佳答案

MisterMiyagi 将我指向 Github 上的 mypy 问题跟踪器,其中指出 Protocol无法匹配数据类:https://github.com/python/mypy/issues/6568

class WithId(typing.Protocol):
id: str


Klass = typing.TypeVar("Klass", bound=WithId)
只需删除 __dataclass_fields__来自 typing.Protocol子类,一切都按预期工作。实际上对于我的代码来说,它是否是数据类并不重要。它只需要一个 idtyping.Protocol 一起使用的字段

关于带有协议(protocol)和 TypeVar 的 Python 类型提示以指定任意数据类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63753566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com