Python dataclass, what’s a pythonic way to validate initialization arguments?

Define a __post_init__ method on the class; the generated __init__ will call it if defined:

from dataclasses import dataclass

@dataclass
class MyClass:
    is_good: bool = False
    is_bad: bool = False

    def __post_init__(self):
        if self.is_good:
            assert not self.is_bad

This will even work when the replace function is used to make a new instance.

Leave a Comment