Dataclasses and Value Objects · practice
Replace an Immutable Value
A frozen
That is already how
The original remains and the operation returns a new value.
Replace selected fields
dataclasses.replace copies a dataclass while changing named fields:
Every field not named in the call is copied. The original cannot be touched.
A small domain
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 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