[英]in python 3.8 how to test a field annotated as Literal in a dataclass is valid at run
Given the following example:给定以下示例:
from typing import Literal
from dataclasses import dataclass
@dataclass
Class Example:
answer: Literal['Y', 'N']
x = Example('N')
field = fields(x)[0]
How can I check that the variable field is of type Literal?如何检查变量字段是否为 Literal 类型?
issubclass(field.type, Literal)
doesn't seem to work. issubclass(field.type, Literal)
似乎不起作用。
Secondly how can I then get the list ['Y', 'N']
from field.type
, so that I could check the value at run time and raise an error when fail = Example('invalid')
其次,我怎样才能从
field.type
获取list ['Y', 'N']
,以便我可以在运行时检查该值并在fail = Example('invalid')
时引发错误
pydantic
does this but you would have to use their drop in dataclass... pydantic
,但你必须使用他们在数据类中的下降......
Literal
is not a normal type that a python object would have at runtime, it doesn't make sense to check that an object is a Literal
Literal
不是 python object 在运行时具有的正常类型,检查 object 是否是Literal
没有意义
You can access the annotations for a class using __annotations__
, following on from your example:您可以使用
__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()
I created a tiny Python library for this purpose: https://github.com/tamuhey/dataclass_utils为此,我创建了一个小型 Python 库: https://github.com/tamuhey/dataclass_utils
This library can be applied for such dataclass that holds another dataclass (nested dataclass), and nested container type (like Tuple[List[Dict...
).该库可应用于包含另一个数据类(嵌套数据类)和嵌套容器类型(如
Tuple[List[Dict...
)的数据类。 Of course, it can test Literal
at runtime.当然,它可以在运行时测试
Literal
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.