Python Glossary Русский

all Python 3copyfunction

copy.copy()

shallow

Creates a shallow copy of an object: the object itself is new, but the nested objects stay shared.

Syntax

copy.copy(obj)

For built-in containers this is exactly list(a), a[:], dict(a) or a.copy() — the function exists so you can copy anything, including instances of your own classes, without knowing the type. For immutables (int, str, a tuple of immutables) copy may hand back the very same object, since there is nothing to copy. Note also that copying a class instance does not call __init__; the contents of __dict__ are transferred directly.

Examples

import copy
a = [1, [2, 3]]
b = copy.copy(a)
b.append(4)
print(a) # → [1, [2, 3]]
b[1].append(99)
print(a) # → [1, [2, 3, 99]]  вложенный общий!
d = {'x': [1, 2]}
d2 = copy.copy(d)
d2['x'] is d['x'] # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy