![](/img/trans.png)
[英]How to declare python dataclass member field same as the dataclass type
[英]in python 3.8 how to test a field annotated as Literal in a dataclass is valid at run
给定以下示例:
from typing import Literal
from dataclasses import dataclass
@dataclass
Class Example:
answer: Literal['Y', 'N']
x = Example('N')
field = fields(x)[0]
如何检查变量字段是否为 Literal 类型? issubclass(field.type, Literal)
似乎不起作用。
其次,我怎样才能从field.type
获取list ['Y', 'N']
,以便我可以在运行时检查该值并在fail = Example('invalid')
时引发错误
pydantic
,但你必须使用他们在数据类中的下降......
Literal
不是 python object 在运行时具有的正常类型,检查 object 是否是Literal
没有意义
您可以使用__annotations__
访问 class 的注释,从您的示例开始:
>>> Example.__annotations__['answer'].__args__
('Y', 'N')
from dataclasses import dataclass
from typing import Literal
from validated_dc import ValidatedDC
@dataclass
class Example(ValidatedDC):
answer: Literal['Y', 'N']
instance = Example('N')
assert instance.is_valid()
instance = Example('X')
assert not instance.is_valid()
为此,我创建了一个小型 Python 库: https://github.com/tamuhey/dataclass_utils
该库可应用于包含另一个数据类(嵌套数据类)和嵌套容器类型(如Tuple[List[Dict...
)的数据类。 当然,它可以在运行时测试Literal
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.