Is Cloning Faster Than Building? The Prototype Pattern in Python
This article explains how the Prototype pattern creates objects by copying configured instances, how __deepcopy__ decides what clones share, how a registry of prototypes works, and why cloning is not automatically faster.
Some objects are expensive or tedious to configure: their construction reads files, parses definitions or sets many attributes, and programs often need many objects that differ from one another in only a few details. The present article examines the Prototype pattern, which creates new objects by copying a configured instance, the prototype, instead of building each one from its constructor. It compares shallow and deep copies, shows how a class controls what its copies share, builds a registry of named prototypes, relates the pattern to factories and measures the claim, frequently repeated, that cloning is faster than construction. Producing a new, independent object from a configured example, while sharing exactly the parts that never change, is the secret weapon of the Prototype pattern.
Cloning with the copy Module
Python implements cloning in the copy module, which offers two operations. A shallow copy, copy.copy, creates a new object whose attributes refer to the same objects as the original; a deep copy, copy.deepcopy, copies those attributes recursively, and records the objects already copied so that shared references and cycles are preserved. The difference becomes visible as soon as an attribute is mutable, as the following example shows.
import copy
class Report:
def __init__(self, title, sections):
self.title, self.sections = title, sections
template = Report("Monthly report", ["Summary", "Figures"])
shallow = copy.copy(template)
deep = copy.deepcopy(template)
shallow.sections.append("Appendix")
deep.sections.append("Risks")
print(template.sections) # Output: ['Summary', 'Figures', 'Appendix']
print(deep.sections) # Output: ['Summary', 'Figures', 'Risks']
print(shallow.sections is template.sections) # Output: True
The section added to the shallow copy appears in the template, because both objects hold the same list, while the deep copy received a list of its own. A prototype whose clones must be independent therefore needs a deep copy of every mutable attribute that the clones will change, and only of those.
Sharing What Is Heavy, Copying What Changes
A plain deep copy duplicates everything, including the parts that justified the prototype in the first place, such as a parsed definition that took time to build and that no clone modifies. A class controls its own copies by defining __deepcopy__, which receives the dictionary of objects already copied, memo, and may share some attributes while copying others. In the following example, every document shares one parsed stylesheet and receives its own list of pages.
import copy
class Stylesheet:
parses = 0
def __init__(self, source):
Stylesheet.parses += 1
self.rules = tuple(line.split(":") for line in source.splitlines())
class Document:
def __init__(self, stylesheet):
self.stylesheet, self.pages = stylesheet, []
def __deepcopy__(self, memo):
clone = copy.copy(self)
clone.pages = copy.deepcopy(self.pages, memo)
return clone
prototype = Document(Stylesheet("h1:bold\np:serif"))
prototype.pages.append(["Cover"])
first, second = copy.deepcopy(prototype), copy.deepcopy(prototype)
first.pages[0].append("Logo")
print(Stylesheet.parses) # Output: 1
print(first.stylesheet is prototype.stylesheet) # Output: True
print(prototype.pages, first.pages) # Output: [['Cover']] [['Cover', 'Logo']]
The stylesheet was parsed once and is shared by the prototype and both clones, which is safe because its rules are stored in a tuple and never change. The pages, which each document modifies, are copied in depth, so the logo added to the first clone does not reach the prototype. The method passes memo on to copy.deepcopy, which keeps shared references and cycles inside the pages intact.
Spawning From Templates: A Registry of Prototypes
Programs that create many variants of a few kinds of object often keep their prototypes in a registry, a dictionary from names to configured instances, and produce each new object by cloning one of them and overriding a few attributes. The registry in the following example refuses overrides for attributes that the prototype does not have, which catches spelling errors at the moment of creation.
import copy
class Message:
def __init__(self, subject, body, priority="normal"):
self.subject, self.body, self.priority = subject, body, priority
self.recipients = []
class Registry:
def __init__(self):
self._prototypes = {}
def register(self, name, prototype):
self._prototypes[name] = prototype
def create(self, name, **overrides):
clone = copy.deepcopy(self._prototypes[name])
for attribute, value in overrides.items():
if not hasattr(clone, attribute):
raise AttributeError(f"{name!r} has no attribute {attribute!r}")
setattr(clone, attribute, value)
return clone
registry = Registry()
registry.register("outage", Message("Service outage", "Work in progress.", "high"))
alert = registry.create("outage", body="Database unavailable.")
alert.recipients.append("[email protected]")
print(alert.subject, alert.priority, alert.body) # Output: Service outage high Database unavailable.
print(registry.create("outage").recipients) # Output: []
try:
registry.create("outage", priorty="low")
except AttributeError as error:
print(error) # Output: 'outage' has no attribute 'priorty'
Each call to create returns an independent message, so the recipient added to one alert does not appear in the next. The prototypes themselves can be configured once, at start-up or from a configuration file, and new variants are registered without writing new classes.
Prototype and Factory
This section relates the pattern to its closest alternative. In languages in which classes are not objects, the Prototype pattern is also a way to create objects without naming their class; in Python, a class is already an object that can be stored and passed, as described in the article devoted to the Factory pattern, so that use of the pattern is rarely needed. The pattern remains useful when the value of the prototype lies in its configured state rather than in its class. For immutable records, dataclasses.replace and copy.replace, available since Python 3.13 and discussed in the article devoted to the Memento pattern, produce a modified copy in one call.
Pitfalls of the Prototype Pattern
A clone is only as independent as the copy that created it, so most of the errors of the pattern concern what is copied and what is shared. Six pitfalls are distinguished, which are the following:
- Shallow copies of mutable state. Clones that share nested lists or dictionaries change one another, as the first example showed.
- Deep copies of heavy resources. Copying parsed definitions, caches or large immutable data wastes the work that the prototype was meant to save.
- Resources that cannot be copied. Locks, open files and sockets raise
TypeErrorwhen deep-copied; a custom__deepcopy__must share them or open new ones. - Copied identities. Fields such as identifiers or creation times are copied with everything else, so each clone must receive new values.
- Modifying the prototype. A change to a registered prototype silently affects every clone created afterwards.
- Assuming that cloning is faster. A deep copy walks the whole object graph in Python code, so it is often slower than running a simple constructor.
The last pitfall is measured in the following example, which compares 2,000 constructions of an object whose constructor builds 200 small dictionaries with 2,000 deep copies of one such object.
import copy
import timeit
class Settings:
def __init__(self):
self.styles = {f"s{i}": {"size": i, "font": "serif"} for i in range(200)}
prototype = Settings()
build = timeit.timeit(Settings, number=2000)
clone = timeit.timeit(lambda: copy.deepcopy(prototype), number=2000)
print(clone > build) # Output: True
On CPython 3.12, the constructions took about 0.05 seconds and the deep copies about 0.41 seconds, so cloning was roughly eight times slower. Cloning saves time only when the constructor performs work that the copy avoids, such as reading a file, querying a database or a long computation, and the claim should be measured in each case.
Choosing How to Create Variants
Consequently, the pattern pays off when configuration is costly and variants differ in a few attributes, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Construction is cheap | Calling the constructor, possibly through a factory |
| Construction reads files, parses data or computes | A configured prototype and deep copies |
| Clones share large read-only data | A custom __deepcopy__ that shares it |
| Many named variants of a few kinds of object | A registry of prototypes with overrides |
| Immutable records with small changes | dataclasses.replace or copy.replace |
| Objects that hold locks, files or sockets | A constructor or a custom copy that opens new resources |
Conclusion
It is concluded that the Prototype pattern creates objects by copying a configured instance, that Python implements it through copy.copy, copy.deepcopy and the hooks __copy__ and __deepcopy__, and that its benefit depends on the cost of construction, which must be measured rather than assumed. This magic depends on deciding, for every attribute, whether the clones share it or receive their own copy, and on resetting the attributes that identify each object. Defining the skeleton of an algorithm once in a base class, while subclasses supply the steps that vary, is the purpose of the Template Method pattern, which is developed in a future article of this series.