0%

Dataclasses and Value Objects · practice

Replace an Immutable Value

A frozen cannot be edited. Programs still need a version with one fact changed.

That is already how behave:

Try it

The original remains and the operation returns a new value.

Replace selected fields

dataclasses.replace copies a dataclass while changing named fields:

Try it

Every field not named in the call is copied. The original cannot be touched.

A small domain can give the change a useful name:

def without_seconds(duration):
    return replace(duration, seconds=0)

What does replace(question, points=5) do?

Use replacement when the old and new values are both meaningful. An adjusted question does not erase the fact that the earlier version existed.

The exercise writes two narrowly named transformations and verifies that each original stays untouched.

Task

Write two that produce new Question values with dataclasses.replace.

worth_more(question, extra) returns a question worth extra more points.

retitled(question, prompt) returns a question with the new prompt.

Each function must leave the original question unchanged and preserve every field it was not asked to change.

Question’s __post_init__ keeps the established validity rules. That means an extra that would make points non-positive and an empty replacement prompt must raise through normal construction.