简体   繁体   English

如何验证 python 数据类属性的枚举值

[英]How to validate the enum values for python dataclass attributes

I have a dataclass and enum values which are as below:我有一个dataclassenum值,如下所示:

@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:一些旁注:

  • By convention class should use the CamelCase naming style按照惯例 class 应该使用 CamelCase 命名风格
  • The order of things matters.事情的顺序很重要。 Python reads code top to bottom, so by having the Enum under the @dataclass you will get a NameError: name 'CheckTheseDataTypes' is not defined Python 从上到下读取代码,因此通过在 @dataclass 下使用枚举,您将得到一个NameError: name 'CheckTheseDataTypes' is not defined

Hope this helps:)希望这可以帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM