我正在尝试构建一个类型化的字典类,类似于NamedTuple
,但是能够对所述元组进行子类化。不幸的是,我发现在想要强制类型的基本构造函数中,我无权访问子类的类型注释。
这是一个最小的例子:
class TypedDict:
def __init__(self, **kwargs):
print(self.__annotations__)
for k, v in kwargs.items():
# Check if k is in self.__annotations__
# Check that v has the same type as self.__annotations__[k]
pass
class A(TypedDict):
field_a: int = 3
class B(A):
field_b: int = 3
在控制台上:
>>> a = A()
{'field_a': <class 'int'>}
>> b = B()
{'field_b': <class 'int'>} # Where is 'field_a'?
如何在TypedDict.__init__
中获得构造函数以同时查看A
的注释?
答案 0 :(得分:1)
您要查找的是typing.get_type_hints
,而不是__annotations__
。 typing.get_type_hints
将合并MRO中所有类的注释,并解析字符串注释。
type_hints = typing.get_type_hints(type(self))
答案 1 :(得分:0)
啊,我有一个使用类mro
的解决方法。
class TypedDict:
def __init__(self, **kwargs):
annotations = {}
for cls in self.__class__.mro():
# __annotations__ is only present when the class has defined annotations.
annotations.update(getattr(cls, "__annotations__", {}))
print(annotations)
for k, v in kwargs.items():
# Check if k is in self.__annotations__
# Check that v has the same type as self.__annotations__[k]
pass
class A(TypedDict):
field_a: int = 3
class B(A):
field_b: int = 3
在控制台上:
>>> a = A()
{'field_a': <class 'int'>}
>> b = B()
{'field_a': <class 'int'>, 'field_b': <class 'int'>}