brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python dataclass(slots=True, frozen=True) blocks typos and mutation

Python
~/tips/tip-python-dataclass-slots-frozen

from dataclasses import dataclass

Makes a dataclass immutable, hashable and typo-proof with two decorator arguments.

I use plain dataclasses for records, and two arguments to the decorator catch a whole class of silent bugs.

from dataclasses import dataclass

@dataclass(slots=True, frozen=True)
class Point:
    x: int
    y: int

slots=True (Python 3.10 and later) stores attributes in slots, which uses less memory and rejects attributes that are not declared as fields. frozen=True makes instances immutable and hashable, so they work as dict keys and set members. Any assignment, such as p.z = 1 or p.x = 5, raises FrozenInstanceError, which is a subclass of AttributeError. Use dataclasses.replace(p, x=5) to get a modified copy. Frozen instances also compare by value, since dataclasses generate __eq__ for you.

Further reading: dataclasses documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link