[英]How to validate the enum values for python dataclass attributes
I have a dataclass
and enum
values which are as below:我有一个
dataclass
和enum
值,如下所示:
@dataclass
class my_class:
id: str
dataType: CheckTheseDataTypes
class CheckTheseDataTypes(str,Enum):
FIRST="int"
SECOND="float"
THIRD = "string"
I want to check whenever this dataclass
is called it should have the datatype
values only from the given enum
list.我想检查每当调用此
dataclass
时,它应该仅具有给定enum
列表中的datatype
值。 I wrote an external validator initially like the below:我最初写了一个外部验证器,如下所示:
if datatype not in CheckTheseDataTypes.__members__:
I am actually looking for something where I don't need this external validation.我实际上是在寻找不需要这种外部验证的东西。 Any help is much appreciated.
任何帮助深表感谢。
You can use the post_init () method to do that.您可以使用post_init () 方法来执行此操作。
from enum import Enum
from dataclasses import dataclass
class CheckTheseDataTypes(str, Enum):
FIRST = "int"
SECOND = "float"
THIRD = "string"
@dataclass
class MyClass:
id: str
data_type: CheckTheseDataTypes
def __post_init__(self):
if self.data_type not in list(CheckTheseDataTypes):
raise ValueError('data_type id not a valid value')
data = MyClass(id='abc', data_type="wrong_type")
A couple of side notes:一些旁注:
NameError: name 'CheckTheseDataTypes' is not defined
NameError: name 'CheckTheseDataTypes' is not defined
Hope this helps:)希望这可以帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.