Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Object-oriented PythonMiddleCommonPractical

Model a test result with a dataclass and reject invalid duration values at construction time.

Answer

Declare the data fields with `@dataclass`, then put invariants that depend on initialized fields in `__post_init__`. This keeps generated `__init__`, `__repr__`, and equality behavior while still enforcing domain rules. Raise a specific standard exception such as `ValueError` when the caller provides a negative duration.

Strong answer includes

  • uses @dataclass for the record
  • validates initialized fields in __post_init__
  • raises a clear exception for invalid input

Practical example

Dataclass with a construction invariant
Python
editable · browser sandbox
Result
Run the code to see the result.

The dataclass generates the constructor and representation; __post_init__ runs immediately after field assignment and enforces the domain rule.

Expected result: TestResult(name='login', status='passed', duration=1.2)

#dataclasses#oop#validation

Sources

dataclasses — Data ClassesPython Software Foundation · Generated dunder methods, field defaults and frozen/eq/order semanticsErrors and ExceptionsPython Software Foundation · try/except/else/finally control flow and exception chaining