Python 3 dataclass initialization

Do dataclasses have a way to add additional initialization aside from what is provided with its built in initializer, without overriding it? Specifically, I want to check some values of a list of integers that is one of the fields in the data class upon initialization.


Solution 1:

As described in the dataclass PEP, there is a __post_init__ method, which will be the last thing called by __init__.

from dataclasses import dataclass

@dataclass
class DataClass: 
    some_field: int

    def __post_init__(self):
        print(f"My field is {self.some_field}")

Defining this dataclass class, and then running the following:

dc = DataClass(1) # Prints "My field is 1"

Would initialize some_field to 1, and then run __post_init__, printing My field is 1.

This allows you to run code after the initialization method to do any additional setup/checks you might want to perform.