CodeBlanks Logo Icon CodeBlanks

__post_init__

Learn post-init logic with __post_init__.

The __post_init__ method

In a dataclass __init__ is auto-generated, but sometimes you need validation or computation after the instance is created. The __post_init__ method is called right after the constructor finishes.

Example: def __post_init__(self):\n if self.value < 0:\n raise ValueError("negative not allowed"). This method runs after the constructor fills the fields. If a negative value is given, the error is raised during instance creation. So you block invalid instances from the start.

Ideal for validation

__post_init__ is the ideal place for validation. Since it runs after the constructor fills all fields, it can reach every field. You check conditions like negative values, empty strings or wrong types and raise an error if needed.

Another use is computing derived fields. Example: in a Rectangle class, you can take w and h fields and compute the area field inside __post_init__. So when the instance is ready, area is also filled.

Practice Add __post_init__ to the Positive class

Start with from dataclasses import dataclass. Define a Positive class with @dataclass; include the field value: int = 0. Add a method def __post_init__(self):; in the body write if self.value < 0: and raise ValueError("negative not allowed"). Then create an instance with p = Positive(5) and print with print(p.value).

Starter code

main.py
# Add __post_init__ to the Positive class

Sample solution

main.py
# Add __post_init__ to the Positive class
from dataclasses import dataclass

@dataclass
class Positive:
    value: int = 0

    def __post_init__(self):
        if self.value < 0:
            raise ValueError("negative not allowed")

p = Positive(5)
print(p.value)

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the __post_init__ parts

Term Meaning
__post_init__ Post-constructor method
__init__ Auto constructor
ValueError Validation error
self.value Validated field

2 When does __post_init__ run?

  • When the class is defined
  • Right after the constructor Correct answer
  • Only on error
  • When the instance is deleted

Explanation: __post_init__ runs right after the constructor finishes.

3 Complete the validation body

Question
    def __post_init__(self):
        if self.value < 0:
            raise ____("negative not allowed")
Answer
    def __post_init__(self):
        if self.value < 0:
            raise ValueError("negative not allowed")

Explanation: ValueError is appropriate for a negative value.

All lessons in Intermediate