2

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.

1 Answer 1

3

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, your second point makes sense. That's why we created a different class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.