Home > Mobile >  How to validate the enum values for python dataclass attributes
How to validate the enum values for python dataclass attributes

Time:11-25

I have a dataclass and enum values which are as below:

@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. 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.

CodePudding user response:

You can use the post_init() method to do that.

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
  • 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

Hope this helps :)

  • Related