Python Glossary Русский

all Python 3copyfunction

copy.deepcopy()

deep

Creates a fully independent deep copy of an object: every nested object is copied too. Unlike list.copy() (a shallow copy), changing a nested item does not affect the original.

Syntax

import copy
copy.deepcopy(obj, memo=None)

A memo dictionary is kept internally, so cycles do not loop forever and an object reachable by two paths stays a single shared object in the copy as well. Not everything is duplicated: functions and classes come back unchanged, while modules, files, sockets and threads cannot be copied at all — deepcopy raises TypeError, so an object holding an open connection cannot be deep-copied without its own __deepcopy__. The recursive walk is expensive, so for plain data structures rebuilding them (or a json round-trip) is often faster.

Examples

import copy
a = [[1, 2], [3, 4]]
b = a.copy(); b[0][0] = 99
print(a)  # → [[99, 2], [3, 4]]  (поверхностная: оригинал изменился)
a = [[1, 2], [3, 4]]
c = copy.deepcopy(a); c[0][0] = 99
print(a)  # → [[1, 2], [3, 4]]   (глубокая: оригинал не тронут)
print(c)  # → [[99, 2], [3, 4]]
print(a is c)  # → False
d = {'x': {'y': 1}}
d2 = copy.deepcopy(d)
print(d2['x'] is d['x'])  # → False (вложенный dict тоже скопирован)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy