117

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

1 Answer 1

228

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.

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

3 Comments

Just as a warning, if you use from attr import dataclass, this would not work!
Thanks! I tried to redefine __init__ and wondered why it is not called and any breakpoints aren't helping :)
@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.

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.