Python 3 dataclass initialization

Question:

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.

Asked By: ICW

||

Answers:

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.

Answered By: ICW
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.