Mutation and Copies
Shared State and Default Factories
BOTIE
Record helpers need to account for that sharing too. PEP 557, proposed in 2017 for the dataclass feature, discusses the problem of mutable defaults and provides default_factory for creating values per instance. The underlying issue is ownership: a collection intended for one record must not accidentally become state shared by unrelated records.
Sources for this history
Why Did Editing the Draft Change the Original?
A record has a list of tags and some nested settings. We give it another variable name so we can edit a draft. After adding a tag to the draft, the original displays it too.
The assignment did not create a separate record. Both names referred to the same object. We need to understand that relationship before choosing when to mutate a value, when to copy it, and how far a copy needs to go.
Sharing is demonstrated inside a private copy of the example. The actual input stays unchanged. Python exercises check real object ownership and deep copies.
Step 1 of 1
Choose How Much Must Be Independent
The original record contains a nested list and a nested settings dictionary.
| Operation | New outer dictionary? | Nested objects independent? |
|---|---|---|
| draft = original | No | No |
| draft = original.copy() | Yes | No; existing nested values are still shared |
| draft = deepcopy(original) | Yes | The ordinary nested lists and dictionaries in this example are copied |
draft = original
- New outer dictionary?
- No
- Nested objects independent?
- No
draft = original.copy()
- New outer dictionary?
- Yes
- Nested objects independent?
- No; existing nested values are still shared
draft = deepcopy(original)
- New outer dictionary?
- Yes
- Nested objects independent?
- The ordinary nested lists and dictionaries in this example are copied
Names Refer to Objects
A new outer record can still contain the same list. Copying that list gives the draft its own later edits.
Add a Draft Tag without Changing the Original
The north report has tags ["raw"]. A reviewed draft needs ["raw", "checked"], while the original must still have ["raw"]. Copying the outer record alone can leave both reports sharing one tag list.
BOTIE
Original tags beside draft tags
- original
- 0raw
- draft
- 0raw
- 1checked
Follow the operations
1. Original report
- house
- north
- tags
- 0raw
2. Copy the report
- original
- house
- north
- tags
- 0raw
- draft
- house
- north
- tags
- 0raw
3. Tag for the draft
checked
4. Add a tag to the draft
- original
- house
- north
- tags
- 0raw
- draft
- house
- north
- tags
- 0raw
- 1checked
5. Compare the two tag lists
- original
- 0raw
- draft
- 0raw
- 1checked
6. Result
- original
- 0raw
- draft
- 0raw
- 1checked
Sharing is demonstrated inside a private copy of the example. The actual input stays unchanged. Python exercises check real object ownership and deep copies.
1. Names Refer to Objects
A variable name is a way to refer to an object. Assigning alias = original gives another name to the same object; it does not ask Python to reconstruct that object. With a mutable dictionary or list, changes through either name can be visible through both.
Mutation changes an existing object. Rebinding a name makes that name refer to a different object. Those operations can look similar on a short line, but their consequences for other names differ. For example, list.append changes the existing list, while assigning a new list to one local name does not redirect another name automatically.
The is operator asks whether two references identify the same object. The == operator asks whether their values compare equal. Equal dictionaries need not be the same dictionary.
Before editing shared data, ask which other names or callers may still depend on the object.
2. A Shallow Copy Keeps References to Nested Values
dict.copy and list.copy create a new outer container. They do not recursively copy every object inside it. If a record’s settings field refers to a dictionary, both outer records can still refer to that same settings dictionary after a shallow copy.
Replacing a top-level field in the copy can leave the original outer dictionary unchanged. Mutating the shared nested value is different. That distinction is why a copy can seem to work for one edit and fail for another.
The program first creates an alias, then a shallow copy. It shows both kinds of sharing directly.
The new outer dictionary does not imply a new object at every nested level.
Trace an Alias and a Shallow Copy
The tag append uses an alias. The settings edit uses a shallow outer copy.
original = {'tags': ['raw'], 'settings': {'reviewed': False}}
alias = original
alias['tags'].append('checked')
print(original['tags'])
shallow = original.copy()
shallow['settings']['reviewed'] = True
print(original['settings']['reviewed'])['raw', 'checked']
TrueBoth observations come from mutations visible through a shared object.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
What happened to the object named original?
Question data
original = {"tags":["raw"]}; draft = original. The program executes draft["tags"].append("checked").3. Copy the Data the New Owner Must Control
For a small nested record made from ordinary dictionaries and lists, deepcopy can construct independent nested values. The edited draft can then acquire its own tag and settings without changing the source record.
That does more work than a shallow copy and may copy data the new owner does not need. Sometimes constructing a new record from selected fields is clearer. Sometimes an immutable representation is suitable. A large array, an open file, or an external connection needs an explicit policy rather than an automatic instruction to deep-copy everything.
The copy module supports custom behavior, and a deep copy is not a promise to duplicate every possible external resource. This lesson’s independent-copy guarantee applies to the ordinary nested data in its examples and exercises.
Choose independence based on the intended edits, not on the word copy alone.
Give the Draft Independent Nested Data
This example starts from a fresh record and changes both nested fields in the copy.
from copy import deepcopy
original = {'tags': ['raw'], 'settings': {'reviewed': False}}
edited = deepcopy(original)
edited['tags'].append('checked')
edited['settings']['reviewed'] = True
print(original)
print(edited){'tags': ['raw'], 'settings': {'reviewed': False}}
{'tags': ['raw', 'checked'], 'settings': {'reviewed': True}}The source still contains its original tags and settings.
4. Ordinary Function Defaults Are Evaluated Once
A function definition is executed when Python reaches def. Its default argument values are evaluated then, not each time the function is called. If a default is a list, later omitted-argument calls can reuse that same list.
The example below intentionally keeps a mutable default. Its second call sees the first note. The earlier first result also refers to that same list, so it changes as more notes are appended.
When each omitted argument should begin with independent state, use a sentinel such as None and create the collection inside the call. When a caller supplies a collection, also decide whether the function may mutate it or must return a new one. Fixing the default alone does not settle that ownership question.
The printed first result changes because it still refers to the shared default list.
Watch the Earlier Result Change
This program demonstrates the bug rather than presenting a recommended default.
def keep_note(note, notes=[]):
notes.append(note)
return notes
first = keep_note('A')
print(first)
second = keep_note('B')
print(second)
print(first)['A']
['A', 'B']
['A', 'B']The first and second results refer to the same accumulating list.
5. Use the Rules of the Actual Container or Library
A dataclass field can use field(default_factory=list) to create a list for each instance. Pydantic uses its own field rules: it copies certain non-hashable defaults and also supports default_factory. Neither behavior changes how an ordinary function default works.
NumPy arrays add another distinction. Some array operations return a view sharing underlying storage, while others copy. Do not infer array ownership from what a list slice or dict.copy did. The NumPy lessons explain those array-specific cases.
A type hint such as list[str] describes contents; it does not make the list immutable. A frozen record also does not automatically freeze every nested mutable object. Ownership and mutation remain part of the interface.
Use the documented behavior of the object you have, and test the particular sharing that matters.
6. Make Mutation Part of the Function Contract
Some functions are meant to change state. A function called append_batch can explicitly update the destination after validating the incoming batch. That can be a reasonable interface when the caller owns the destination and expects the change. The earlier dataclass lesson’s add_tag helper also has an explicit mutation agreement.
Here we name the new transformation with_tag because it promises a new record while preserving its input. It is not the same helper with a silently changed agreement. Its tests should compare both the returned record and the original. For nested data, change a nested value in the result after the call and confirm that the original remains independent.
Avoid a global collection that silently accumulates results across calls. It makes a function’s behavior depend on earlier work that its arguments do not show. If persistent state is needed, give it a named owner and a clear lifetime.
The important distinction is whether the actual change matches what the caller was promised.
7. Test More than Equal Printed Values
Two records can print equal values while still sharing mutable children. A useful independence test edits the returned child and checks the original afterward. That exercise reveals a shallow copy even when the original output looked correct.
Call defaulted functions more than once. A test that runs only a single call cannot reveal state leaking into the next omitted-argument call. Include the case where a caller supplies its own list, because that has a separate mutation policy.
The workshop shows original and draft tag lists after a private edit. Its copy control makes sharing visible without changing the actual example input. The programming exercises test real Python mutation and nested copies.
Inspect the relationship after a change, not only the values before the change.
Check yourself
Questions on Parts 1 to 7
Question 1 of 6
Which statement can still be false?
Question data
Two separately created dictionaries have equal fields and values.Try it with Botie
Build with Botie
Write and run Python