Special Method Protocols

__replace__() — other protocol

Implement copy.replace() (Python 3.13+). Return a new instance of the same type with selected fields changed; retain unchanged fields and reject unsupported field names. The original must not be mutated.

Formal Syntax & Structure

python syntaxpython
def __replace__(self, /, **changes):

Parameters & Attributes

NameTypeDescription
**changesdictFields to replace.

Return Value

object

New instance with replacements.

Working Example

Example Snippetpython
import copyclass Label:    def __init__(self,text): self.text=text    def __replace__(self, /, **changes):        if set(changes)-{"text"}: raise TypeError("unknown field")        return Label(changes.get("text",self.text))def demo():    original=Label("old"); changed=copy.replace(original,text="new")    return original.text,changed.textprint(demo())
Python Reference