🐍 Python - Cloning Objects
Updated at 2018-06-11 01:50
Use collection factory functions to create shallow copies.
new_list = list(original_list)
new_dict = dict(original_dict)
new_set = set(original_set)
Use copy
package to create collection deep copies.
import copy
xs = [[1, 2], [4, 5], [7, 8]]
ys = copy.deepcopy(xs)
assert xs == ys
assert xs is not ys
xs[1][0] = 'X'
assert xs != ys
Use copy
package to create object copies. You can customize the copy behavior with __copy__
and __deepcopy__
.
import copy
class Point:
def __init__(self, x: float, y: float) -> None:
self.x: float = x
self.y: float = y
class Rectangle:
def __init__(self, top_left: Point, bottom_right: Point) -> None:
self.top_left: Point = top_left
self.bottom_right: Point = bottom_right
a = Point(10, 20)
b = copy.copy(a)
assert a.x == b.x
assert a.y == b.y
assert a is not b
c = Rectangle(a, b)
d = copy.copy(c) # BAD, doesn't duplicate the points
e = copy.deepcopy(c) # GOOD, duplicates the points
assert a is d.top_left and b is d.bottom_right
assert a is not e.top_left and b is not e.bottom_right
Source
- Python Tricks The Book, Dan Bader
- Fluent Python, Luciano Ramalho