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.
1 Answer
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.
3 Comments
Meysam Sadeghi
Just as a warning, if you use
from attr import dataclass, this would not work!wowkin2
Thanks! I tried to redefine
__init__ and wondered why it is not called and any breakpoints aren't helping :)Stephan Samuel
@wowkin2 if you decorate with
@dataclass(init=False), your __init__ gets called. This is contrary to the question asked (which asks specifically, "... without overriding it") though: you are then responsible for writing your own __init__ entirely, thus defeating some of the benefits of dataclass.