Python Glossary Русский

Python 3.13+copyfunction

copy.replace()

field replacement

Creates a copy of an object of the same type with some fields replaced. Works for dataclasses, namedtuples, datetime and any class with __replace__.

Syntax

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

It is a common façade: copy.replace(obj, **changes) just calls obj.__replace__(**changes), so the same code updates a dataclass, a namedtuple (instead of _replace) and a date/datetime. A plain class without __replace__ raises TypeError rather than making a shallow copy — use copy.copy for that. An unknown field name is a TypeError too, and a dataclass field with init=False cannot be passed. The copy is shallow: nested lists stay shared. New in 3.13; older versions need dataclasses.replace or _replace.

Examples

import copy
from collections import namedtuple
from dataclasses import dataclass
Point = namedtuple('Point', 'x y')
@dataclass(frozen=True)
class User:
    name: str
    age: int
print(copy.replace(Point(1, 2), y=5))  # → Point(x=1, y=5)
print(copy.replace(User('Ann', 30), age=31))  # → User(name='Ann', age=31)
import copy
class Plain:
    pass
try:
    copy.replace(Plain())
except TypeError as e:
    print(e)  # → replace() does not support Plain objects
import copy
class Money:
    def __init__(self, amount, currency):
        self.amount, self.currency = amount, currency
    def __replace__(self, **changes):
        return Money(changes.get('amount', self.amount), changes.get('currency', self.currency))
m = copy.replace(Money(10, 'RUB'), amount=25)
print(m.amount, m.currency)  # → 25 RUB

See also

Open in the full glossarydocs.python.orgReport an inaccuracy