问题描述
我可以在从本地dict
进行子类化时做到这一点,但不能使用键入的版本。这是代码:
from typing import TypedDict
class Typed(TypedDict):
x: int
def __str__(self):
return "str-typed"
class Native(dict):
def __str__(self):
return "str-native"
typed = Typed(x=1)
print("typed =",typed)
native = Native(x=1)
print("native =",native)
assert typed == native
及其结果:
$ python typed_dict.py
typed = {'x': 1}
native = str-native
$ mypy typed_dict.py
typed_dict.py:7: error: Invalid statement in TypedDict definition; expected "field_name: field_type"
Found 1 error in 1 file (checked 1 source file)
有什么建议吗?
解决方法
调用Typed
会创建一个常规词典。您编写的方法不会执行任何操作,因为typed
不是Typed
的实例,并且没有Typed
的任何方法。
虽然从技术上可以在运行时禁用该行为(在当前的3.8实现中,del Typed.__new__
可以做到),但是mypy仍然不满意。 TypedDict
的目的是
class Foo(typing.TypedDict):
x: int
y: str
d: Foo = {'x': 1,'y': 'blah'}
类型检查。 TypedDict
子类旨在表示具有特定字符串键的常规字典的静态类型。不应将其用作自己的单独运行时类型。
此外,del Typed.__new__
还会查看实施细节,如有更改,恕不另行通知。