如何解决如何在 TypedDict 中覆盖 __getitem__?
我正在尝试创建一个 TypedDict
子类,如果某个键会导致 None
并且该键是 KeyError
注释的一部分,该子类将返回 TypedDict
如Optional
。我意识到这不太可能,因为 TypedDict
不能被子类化,除非定义注释。有没有其他雄辩的方法来做到这一点?
这是我想要做的:
from typing import TypedDict,get_args,get_origin
class FilledTypedDict(TypedDict):
def __getitem__(self,k):
if k in self.__annotations__:
annotation = self.__annotations__[k]
if get_origin(annotation) is Union and type(None) in get_args(annotation):
return None
return super().__getitem__(k)
这给了我一个 TypedDict classes can contain only type annotations
。我该如何解决这个问题?
解决方法
你没有。 TypedDict
不是一个适当的类型,它是具有明确定义项的常规 dict
的表示。
重点是没有 TypedDict
的实例,任何具有正确项的 dict
都可以分配给 TypedDict
变量。
from typing import TypedDict
class TD(TypedDict):
a: int
b: str
print(type(TD(a=1,b="two"))) # <class 'dict'>
td: TD = {"a": 1,"b": "two"} # valid
这使得无法向 TypedDict
添加行为,因为它必须始终与 dict
行为完全匹配。
PEP 589 –– TypedDict - 不允许使用方法,因为 TypedDict 对象的运行时类型将始终只是 dict
(它永远不是 dict
的子类)。
可以做的是通过将缺失值显式设置为 TypedDict
来满足“Optional
与 None
值”类型。
from typing import Optional,TypedDict
class Call(TypedDict):
who: str
when: Optional[str]
call: Call
call = Call(who="Gwen",when="tomorrow") # valid
call = {"who": "me","when": None} # valid
call = {"who": "us"} # error: Missing key 'when' for TypedDict "Call"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。