Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

dataclasses.replace

Constructs another instance of the same data class while overriding selected initialization fields.

Version: Python 3.14; repository image, production runtime not attested

Syntax

dataclasses.replace(obj, /, **changes)

Constructs another instance of the same data class while overriding selected initialization fields.

The initializer runs again for the new object. The original instance retains its previous field values.

Pass an instance and named changes to construct a new instance of its type. The generated initializer invokes __post_init__ again, allowing derived fields to be recalculated. Replacing an init=False field raises TypeError; required InitVar inputs without defaults must be supplied. The example creates priority 8 while the original frozen Job still has 2. CPython 3.14.9 raises TypeError both for an init=False field and for an omitted required InitVar. The 3.14 documentation lists ValueError for the init=False case.

from dataclasses import dataclass, field, replace
@dataclass
class Price:
    base: int
    total: int = field(init=False)
    def __post_init__(self):
        self.total = self.base * 2
p = Price(3)
assert replace(p, base=5).total == 10 and p.total == 6
try:
    replace(p, total=99)
except TypeError:
    pass
else:
    raise AssertionError
from dataclasses import InitVar
@dataclass
class Seed:
    value: InitVar[int]
try:
    replace(Seed(4))
except TypeError:
    pass
else:
    raise AssertionError

Examples

import dataclasses
@dataclasses.dataclass(frozen=True)
class Job:
    priority: int

a = Job(2)
b = dataclasses.replace(a, priority=8)
print(a.priority, b.priority, a is b)

Result

2 8 False

Pass an instance and named changes to construct a new instance of its type. The generated initializer invokes `__post_init__` again, allowing derived fields to be recalculated. Replacing an init=False field raises TypeError; required InitVar inputs without defaults must be supplied. The example creates priority 8 while the original frozen Job still has 2. CPython 3.14.9 raises TypeError both for an init=False field and for an omitted required InitVar. The 3.14 documentation lists ValueError for the init=False case.

Sources