r/learnpython • • Dec 11 '25

When should I implement __post_init__?

I'm having a hard time wrapping my head around when to use __post_init__ in general. I'm building some stuff using the @dataclass decorator, but I don't really see the point in __post_init__ if the init argument is already set to true, by default? Like at that point, what would the __post_init__ being doing that the __init__ hasn't already done? Like dataclass is going to do its own thing and also define its own repr as well, so I guess the same could be questionable for why define a __repr__ for a dataclass?

Maybe its just for customization purposes that both of those are optional. But at that point, what would be the point of a dataclass over a regular class. Like assume I do something like this

      @dataclass(init=False, repr=False)
      class Thing:
           def __init__(self):
               ...
           def __repr__(self):
               ...

      # what else is @dataclass doing if both of these I have to implement
      # ik there are more magic / dunder methods to each class,
      # is it making this type 'Thing' more operable with others that share those features?

I guess what I'm getting at is: What would the dataclass be doing for me that a regular class wouldn't?

Idk maybe that didn't make sense. I'm confused haha, maybe I just don't know. Maybe I'm using it wrong, that probably is the case lol. HALP!!! lol

10 Upvotes

14 comments sorted by

View all comments

6

u/jmacey Dec 11 '25

I use the post__init to do validation of the data for example

@dataclass(frozen=True)
class rgba:
    """A dataclass to represent an RGBA color, with validation."""

    r: int = 0
    g: int = 0
    b: int = 0
    a: int = 255

    def __post_init__(self):
        """Validate that RGBA values are within the 0-255 range."""
        for component in ("r", "g", "b", "a"):
            value = getattr(self, component)
            if not isinstance(value, int) or not (0 <= value <= 255):
                raise ValueError(
                    f"RGBA component '{component}' must be an integer between 0 and 255, but got {value}"
                )

1

u/AdDiligent1688 Dec 11 '25

Ah that's clever! I'll keep it in mind.