Python Glossary Русский

all Python 3copyterm

Copying pitfalls

pitfalls

The usual mistakes: mutable default arguments, circular references, and shared state left behind by a shallow copy.

Syntax

# Используй copy/deepcopy для безопасного копирования мутируемых объектов

The key split: a slice lst[:], dict.copy() and copy.copy() duplicate only the top level — nested lists and dicts stay shared, so editing inside the copy shows up in the original. copy.deepcopy() recurses all the way down and survives circular references (it remembers already-copied objects in a memo), but pays in speed and memory, so keep it out of hot loops. The mutable default def f(lst=[]) is a separate trap: it is evaluated once when the function is defined, not per call — use None and build the list inside the body.

Examples

import copy
# Mutable default — антипаттерн:
def bad(lst=[]):
    lst.append(1); return lst
bad(); bad() # → [1, 1]  один объект!
import copy
# Циклическая ссылка:
a = []
a.append(a)
b = copy.deepcopy(a)  # deepcopy справляется
b is a # → False
import copy
# Shallow: одинаковые вложенные объекты
x = [[0]*3]*3
y = copy.copy(x)
y[0][0] = 9
print(x) # → [[9,0,0],[9,0,0],[9,0,0]]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy