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's dataclasses.replace copies an object with one field changed

Python
~/tips/tip-python-dataclasses-replace-copy-with-change

from dataclasses import dataclass, replace

replace() makes a new dataclass instance with the fields you name changed.

Frozen dataclasses are nice until you need a slightly different copy. dataclasses.replace makes one without you listing every field.

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Job:
    name: str
    retries: int = 3

a = Job("backup")
b = replace(a, retries=0)
print(a, b)

It printed:

Job(name='backup', retries=3) Job(name='backup', retries=0)

The original stays as it was, and the new object gets all other fields copied over. It works on non-frozen dataclasses too.

The caveat is that replace calls the constructor again, so __post_init__ runs for the copy as well. A print in __post_init__ fires once for the original and once for the replacement. If that method does something expensive or has side effects, keep that in mind. The copy is also shallow, so a list inside the object is shared between both. Passing anything that is not a dataclass instance, such as a dict, raises a TypeError.

Another caveat: fields declared with init=False cannot be passed to replace. On Python 3.11 this raises ValueError: field b is declared with init=False, it cannot be specified with replace(). Such fields are not copied over either; the new object computes them itself, through the default or __post_init__.

Further reading: dataclasses.replace

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