Python Frozen Dataclasses and replace
A Python frozen dataclass refuses any change to its fields once it is made. replace() makes a changed copy instead and leaves the original as it was.
Read Python Dataclasses and Try and except first. This lesson freezes a dataclass, catches a refused change and makes changed copies with replace(). Both come from Python's standard dataclasses module, so nothing needs installing.
Frozen fields
Write frozen=True in brackets after @dataclass. You can still read every field, but assigning to one raises an error.
from dataclasses import dataclass@dataclass(frozen=True)class Point: x: int y: intstart = Point(2, 5)print(start.x)start.x = 7 # this line raises FrozenInstanceErrorThis prints 2, then stops with FrozenInstanceError: cannot assign to field 'x'. The generated __init__() still stores the fields when the object is made. Only later assignments are refused.
Freeze a class whose objects are values that should never change, such as a point, a colour or a price. Code that is handed one can trust it to stay the same. Leave frozen=True out when an object is meant to change, such as a tank that fills up.
Catch a refused change
Import FrozenInstanceError from dataclasses to catch the error and carry on.
from dataclasses import dataclass, FrozenInstanceError@dataclass(frozen=True)class Point: x: int y: intstart = Point(2, 5)try: start.x = 7except FrozenInstanceError: print("refused")print(start)This prints refused, then Point(x=2, y=5). The object still holds the values it was made with.
Make a changed copy
replace() builds a new object from an old one. Import it from dataclasses beside dataclass. Pass the object first, then field=value for each field that changes.
from dataclasses import dataclass, replace@dataclassclass Ticket: seat: str price: intticket = Ticket("A4", 10)cheaper = replace(ticket, price=8)print(ticket)print(cheaper)This prints Ticket(seat='A4', price=10), then Ticket(seat='A4', price=8). The copy takes seat from ticket and gets the new price. ticket itself does not change.
replace() works on every dataclass, frozen or not. On a plain one you choose: ticket.price = 8 changes the one object, while replace() keeps the old object beside a new one. On a frozen one, replace() is the only way to get a changed version.
Name the fields to change
replace() takes the fields to change as keywords only. A name the class does not have raises an error.
from dataclasses import dataclass, replace@dataclassclass Ticket: seat: str price: intticket = Ticket("A4", 10)print(replace(ticket, cost=8)) # this line raises TypeErrorThis stops with TypeError: Ticket.__init__() got an unexpected keyword argument 'cost'. replace() makes the copy by calling the generated __init__(), so a wrong name fails there. A value with no name, as in replace(ticket, 8), is a TypeError too. Because __init__() runs, a __post_init__() check also runs on the copy.
Note: frozen=True stops assignment to the fields only. If a field holds a list, append() can still change that list. The examples here keep to numbers and strings.
See also: Python Dataclass Validation with post_init, Python Dataclass Methods.
Your turn
Make Badge frozen, so the change to badge.level is refused. Put that change inside try, and print badges can't change when it is refused.
badges can't change Badge(owner='Ada', level=2)
from dataclasses import dataclass, FrozenInstanceError@dataclassclass Badge: owner: str level: intbadge = Badge("Ada", 2)# make Badge frozen, then put the next line inside try and print badges can't change when it is refusedbadge.level = 3print(badge)