Python 3 dataclass initialization

PythonPython 3.x

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionICWView Question on Stackoverflow
Solution 1 - PythonICWView Answer on Stackoverflow