ZetCode

Python __copy__ Method

Last modified November 17, 2026 Python 3.15

The copy.copy() function makes a shallow copy of an object: the top-level object is new, but the values it refers to are shared. A class can take control of that process by defining __copy__, which copy.copy() calls instead of the generic machinery. This article explains the default behaviour, the dispatch order, the difference between shallow and deep copies, and the cases where returning the original object is the right answer.

The default shallow copy

Without __copy__, copy.copy() creates a new instance of the same class and copies the instance dictionary. The new object has its own __dict__, but the values inside it are the same objects as before. Mutable attributes are therefore shared between the original and the copy.

default_copy.py
import copy


class Document:
    def __init__(self, title, tags):
        self.title = title
        self.tags = tags

    def __repr__(self):
        return f"Document({self.title!r}, {self.tags!r})"


original = Document("Notes", ["python", "copy"])
duplicate = copy.copy(original)

print(original is duplicate)
print(original.__dict__ is duplicate.__dict__)
print(original.tags is duplicate.tags)
duplicate.tags.append("shared")
print(original.tags)

The two documents are different objects with different dictionaries, but tags points to one list. Appending through the copy is visible in the original, which is exactly what "shallow" means. This default is often sufficient, and the copies made by slicing a list or calling dict.copy() follow the same rule.

$ python default_copy.py
False
False
True
['python', 'copy', 'shared']

How copy.copy chooses a method

copy.copy() first looks for __copy__ on the class. If it is absent, the function falls back to the reduction protocol (__reduce_ex__ or __reduce__) and then to the registrations in copyreg. A class can therefore define both a custom copy method and a reduction method, and the copy method wins.

dispatch.py
import copy


class Widget:
    def __init__(self, name):
        self.name = name

    def __copy__(self):
        print("__copy__ used")
        return Widget(self.name)

    def __reduce_ex__(self, protocol):
        print("__reduce_ex__ used")
        return (Widget, (self.name,))


w = Widget("button")
shallow = copy.copy(w)
print(shallow is w)

w2 = Widget("slider")
deep = copy.deepcopy(w2)
print(deep is w2)
print(deep.name)

The shallow copy prints __copy__ used, while the deep copy prints __reduce_ex__ used and never calls __copy__. This is an important detail: __copy__ controls only copy.copy(). Deep copying looks for __deepcopy__ and otherwise reconstructs the object through the reduction protocol.

$ python dispatch.py
__copy__ used
False
__reduce_ex__ used
False
slider

Implementing __copy__

A custom __copy__ receives only self and returns the new object. The method below builds a fresh Box from the same coordinates, so the copy does not share any mutable state with the original and does not depend on the default dictionary copying.

basic_copy.py
import copy


class Box:
    created = 0

    def __init__(self, width, height):
        Box.created += 1
        self.width = width
        self.height = height

    def __copy__(self):
        print("__copy__ called")
        return Box(self.width, self.height)

    def __repr__(self):
        return f"Box({self.width}, {self.height})"


original = Box(10, 20)
before = Box.created
duplicate = copy.copy(original)

print(duplicate)
print(original is duplicate)
print(Box.created - before)
print(original.width is duplicate.width)

The hook runs once, and the constructor runs once as part of it, which the counter confirms. The integers are immutable, so sharing them is harmless and the last line prints True. The explicit constructor call makes the copy semantics obvious, but it also means subclasses with extra constructor arguments need their own __copy__.

$ python basic_copy.py
__copy__ called
Box(10, 20)
False
1
True

Shallow and deep copies side by side

A shallow copy duplicates the container but not its contents, while a deep copy recursively duplicates everything reachable from the object. The following class defines __copy__ but no __deepcopy__, so copy.deepcopy() uses the reduction protocol and copies the song list independently.

shallow_deep.py
import copy


class Playlist:
    def __init__(self, name, songs):
        self.name = name
        self.songs = songs

    def __copy__(self):
        print("shallow copy")
        return Playlist(self.name, self.songs)

    def __repr__(self):
        return f"Playlist({self.name!r}, {self.songs!r})"


original = Playlist("Road trip", ["Song A", "Song B"])
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original.songs.append("Song C")

print(shallow)
print(deep)
print(shallow.songs is original.songs)
print(deep.songs is original.songs)
print(deep.name is original.name)

The shallow copy shows the appended song because it shares the list. The deep copy keeps its own list, so it still has two songs. The name string is shared in both cases because strings are immutable and deep copying does not need to duplicate them; the identity check at the end prints True.

$ python shallow_deep.py
shallow copy
Playlist('Road trip', ['Song A', 'Song B', 'Song C'])
Playlist('Road trip', ['Song A', 'Song B'])
True
False
True

Objects with __slots__

A class that declares __slots__ has no instance dictionary, but that does not prevent copying. Providing __copy__ is still the clearest option, and the default reduction path also handles slots when the hook is absent. The example defines both variants to show that each produces a usable copy.

slots_copy.py
import copy


class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __copy__(self):
        return Point(self.x, self.y)

    def __repr__(self):
        return f"Point({self.x}, {self.y})"


class DefaultPoint:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"DefaultPoint({self.x}, {self.y})"


p = copy.copy(Point(1, 2))
q = copy.copy(DefaultPoint(3, 4))

print(p)
print(type(p).__name__)
print(q)
print(q.x, q.y)

Both copies carry the coordinates, and both have the expected type. With __slots__, copy.copy() cannot simply duplicate __dict__; the reduction protocol serializes the slot values instead. A hand-written __copy__ avoids that machinery but must list every slot that belongs to the state.

$ python slots_copy.py
Point(1, 2)
Point
DefaultPoint(3, 4)
3 4

Immutable objects and returning self

If an object cannot change, a copy does not need to be a new object, and returning self is both correct and cheap. Python applies the same idea to integers, strings, and tuples, where copy.copy() often returns the original object. The class below enforces immutability by blocking attribute assignment and confirms the identity of the copy.

immutable_copy.py
import copy


class Color:
    __slots__ = ("_name",)

    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    def __copy__(self):
        return self

    def __repr__(self):
        return f"Color({self.name!r})"


class FrozenPoint:
    def __init__(self, x, y):
        object.__setattr__(self, "x", x)
        object.__setattr__(self, "y", y)

    def __setattr__(self, name, value):
        raise AttributeError("FrozenPoint is immutable")

    def __copy__(self):
        return self

    def __repr__(self):
        return f"FrozenPoint({self.x}, {self.y})"


number = 42
text = "text"
pair = (1, 2)

c = Color("red")
print(copy.copy(c) is c)
print(copy.copy(number) is number)
print(copy.copy(text) is text)
print(copy.copy(pair) is pair)

p = FrozenPoint(3, 4)
print(copy.copy(p) is p)

try:
    c.name = "blue"
except AttributeError as e:
    print(type(e).__name__, e)

The first five lines print True: the copies are the originals. This is safe only when no reachable state can be mutated. Color exposes name as a read-only property, and the last block confirms that assigning to it fails. A class with writable attributes should not return self, because callers would receive a shared, changeable object instead of an independent copy.

$ python immutable_copy.py
True
True
True
True
True
AttributeError property 'name' of 'Color' object has no setter

Best practices

Copy semantics are part of the public contract, so decide them deliberately:

Source

copy - Python documentation

object.__copy__ - Python documentation

object.__reduce_ex__ - Python documentation

In this article we have implemented the __copy__ method. We have covered the default shallow copy, the dispatch order of copy.copy(), custom copy construction, the difference from a deep copy, classes with __slots__, and the immutable-object shortcut. For related topics, see Python __deepcopy__ method, Python copy by value and by reference, Python __reduce__ method, and Python __new__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.