frozen
- Python course
- Intermediate
- Lesson 55/116
- 4 min
Learn immutable data classes with @dataclass(frozen=True).
frozen=True
@dataclass(frozen=True) makes the dataclass immutable. After creating an instance you cannot assign new values to its fields; trying raises FrozenInstanceError. This is ideal for constant values.
Example: @dataclass(frozen=True)\nclass Color:\n r: int = 0\n g: int = 0\n b: int = 0. After c = Color(255, 0, 0), writing c.r = 100 raises an error. hash(c) works; frozen classes are hashable.
frozen and hash
frozen dataclasses are hashable. So you can use their instances as dictionary keys or set members. hash(c) returns a number; two instances with the same values give the same number.
This is useful for constant value types like coordinates, colors or currencies. You represent values you want to store as dictionary keys with frozen dataclasses; since they do not change, the key is not corrupted.
Practice Make the Color class frozen
Start with from dataclasses import dataclass. Define a Color class with @dataclass(frozen=True); include fields r: int = 0, g: int = 0 and b: int = 0. Then create an instance with c = Color(255, 0, 0) and print with print(c.r).
Starter code
# Write the Color class as a frozen dataclassSample solution
# Write the Color class as a frozen dataclass
from dataclasses import dataclass
@dataclass(frozen=True)
class Color:
r: int = 0
g: int = 0
b: int = 0
c = Color(255, 0, 0)
print(c.r)Expected output
255
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does frozen=True prevent?
- Field assignment Correct answer
- Instance creation
- Class definition
- Print calls
Explanation: frozen=True prevents field assignment after the instance is created.
2 frozen decorator line
@dataclass(____)
class Color:
r: int = 0
g: int = 0
b: int = 0
@dataclass(frozen=True)
class Color:
r: int = 0
g: int = 0
b: int = 0
Explanation: frozen=True makes the dataclass immutable.
3 Match the frozen parts
| Term | Meaning |
|---|---|
frozen=True |
Argument |
Color(255, 0, 0) |
Instance |
FrozenInstanceError |
Assignment error |
hash(c) |
Hash call |