Python copy.replace() Function

Python copy.replace() creates a new object of the same type while replacing selected fields. It was added in Python 3.13 and provides one common API for immutable-style updates across supported object types.

The function is useful when you want to keep the original object unchanged and create a modified version with only a few different values. It works with named tuples, dataclass instances, and classes that implement the __replace__() protocol.

copy.replace() Syntax

from copy import replace

new_object = replace(original, field=value)

The first argument is the object to copy. Keyword arguments identify the fields that should receive new values. The result is a new object of the same supported type.

copy.replace() is not the same as copy.copy() or copy.deepcopy(). It performs a field-based replacement operation supported by specific object types.

Replace Fields in a Dataclass

The following example uses a frozen dataclass. The original Product remains unchanged while copy.replace() creates another Product with a different price and stock value.

Example:

from copy import replace
from dataclasses import dataclass

@dataclass(frozen=True)
class Product:
    name: str
    price: int
    stock: int

original = Product("Keyboard", 2500, 12)

# Create a new Product with selected fields changed.
updated = replace(original, price=2200, stock=10)

print(original)
print(updated)

Output:

Product(name='Keyboard', price=2500, stock=12)
Product(name='Keyboard', price=2200, stock=10)

Use copy.replace() with Named Tuples

Named tuples also support replacement because their values are identified by field names.

Example:

from copy import replace
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])

start = Point(4, 7)

# Change only the y field.
moved = replace(start, y=12)

print(start)
print(moved)

Output:

Point(x=4, y=7)
Point(x=4, y=12)

How It Differs from dataclasses.replace()

The dataclasses module already provides dataclasses.replace() for dataclass instances. copy.replace() gives you a higher-level function that can work with several supported object families through the same interface.

Function Purpose Typical input
copy.copy() Create a shallow copy Many Python objects
copy.deepcopy() Recursively copy nested content Many Python objects
copy.replace() Create a new object with selected fields changed Dataclasses, named tuples, compatible custom classes
dataclasses.replace() Replace fields in a dataclass Dataclass instances

Understand Shallow Replacement

Replacing fields does not automatically deep-copy nested mutable values. Fields that you do not replace can still refer to the same nested objects as the original.

Example:

from copy import replace
from dataclasses import dataclass

@dataclass(frozen=True)
class Team:
    name: str
    members: list[str]

members = ["Asha", "Mia"]
first = Team("Blue", members)

# The members list is reused because it is not replaced.
second = replace(first, name="Green")

members.append("Noah")

print(first.members)
print(second.members)

Output:

['Asha', 'Mia', 'Noah']
['Asha', 'Mia', 'Noah']

If the nested data must be independent, create or copy that nested value separately and pass it as a replacement.

Support copy.replace() in Your Own Class

A custom class can participate in this protocol by defining __replace__(). The method receives keyword changes and returns a new object of the same type.

class Settings:
    def __init__(self, theme, page_size):
        self.theme = theme
        self.page_size = page_size

    def __replace__(self, **changes):
        # Use current values when a field is not replaced.
        return Settings(
            changes.get("theme", self.theme),
            changes.get("page_size", self.page_size)
        )

Common Mistakes

  • Using it on any arbitrary object: copy.replace() only works with supported object types or classes that implement __replace__().
  • Expecting a deep copy: unchanged nested mutable fields can still be shared.
  • Misspelling a field name: supported types normally reject unknown replacement fields instead of silently adding them.
  • Mutating the result unnecessarily: the feature is most useful when you intentionally work with value-like or immutable-style objects.

When to Use copy.replace()

  • Create a modified configuration value without changing the original.
  • Update frozen dataclass instances in a clear, declarative way.
  • Write generic code that can replace fields across several compatible record-like types.
  • Implement functional-style transformations where previous values should remain available.

Best Practices

  • Replace only the fields that actually change.
  • Keep field names stable and meaningful when designing custom replaceable classes.
  • Copy nested mutable values separately when isolation matters.
  • Prefer ordinary mutation when an object is intentionally mutable and no historical value must be preserved.

Version Requirements

copy.replace() requires Python 3.13 or later. If your project supports older Python versions, keep using the type-specific replacement API, such as dataclasses.replace(), or provide a compatibility helper until the minimum runtime is upgraded.

`r`n

Conclusion

copy.replace() gives Python a standard way to create field-modified copies of supported record-like objects. It keeps the original value intact, works naturally with dataclasses and named tuples, and can be extended through __replace__(). Use it when explicit field replacement makes your data flow clearer than in-place mutation.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram