Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Read only (frozen) Dataclass

  • @dataclass(frozen = True) makes the class immutable
from dataclasses import dataclass

@dataclass(frozen = True)
class Point():
    x : float
    y : float
    name : str
from shapes import Point

p1 = Point(2, 3, 'left')
print(p1)           # Point(x=2, y=3, name='left')
# p1.x = 7          # dataclasses.FrozenInstanceError: cannot assign to field 'x'
# p1.color = 'blue' # dataclasses.FrozenInstanceError: cannot assign to field 'color'