0

Sometimes we don't want things to change. In the code below, my original Things are mutated, even though I made a copy of the list containing them. I'm not that surprised, but I'd like to know how to store my original object properties so I can restore my things list to exactly how it was when first created.

class Thing:
    def __init__(self, x):
        self.x = x

    def __str__(self):
        return str(self.x)

things = [Thing(10), Thing(20)]
original_things = things.copy()

for thing in things:
    print(thing)
print("All change")
things[0].x = 30
things[1].x = 40
print("Back to the beginning?")
things = original_things
for thing in things:
    print(thing)
Robin Andrews
  • 3,514
  • 11
  • 43
  • 111

1 Answers1

0

Read the docs, Luke!

Python documentation for lists says:

list.copy(x)

Return a shallow copy of the list. Equivalent to a[:].

Therefore, bar_list = foo_list.copy() is equivalent to bar_list = foo_list.

As per @Gphilo, what you want is copy.deepcopy:

from copy import deepcopy
class Thing:
    def __init__(self, x):
        self.x = x

    def __str__(self):
        return str(self.x)

things = [Thing(10), Thing(20)]
original_things = deepcopy(things)

for thing in things:
    print(thing)
print("All change")
things[0].x = 30
things[1].x = 40
print("Back to the beginning!")
things = original_things
for thing in things:
    print(thing)

Output:

10
20
All change
Back to the beginning!
10
20
Community
  • 1
  • 1
gust
  • 878
  • 9
  • 23