13

In the following example I would expect deepcopy to create a copy of field and not just copy the reference. What happens here and is there an easy way around it?

from copy import deepcopy

class Test:
    field = [(1,2)]

t1 = Test()
t2 = deepcopy(t1)

t2.field[0]=(5,10)

print t1.field # [(1,2)] expected but [(5,10)] obtained
print t2.field # [(5,10)] expected

Output:

[(5, 10)]
[(5, 10)]
Elrond1337
  • 424
  • 1
  • 5
  • 16
  • possible duplicate of [How to copy a python class?](http://stackoverflow.com/questions/9541025/how-to-copy-a-python-class) – Vajk Hermecz Feb 13 '14 at 11:10

2 Answers2

15

Deep copying (by default) only applies to instance level attributes - not class level - It doesn't make much sense that there's more than one unique class.attribute...

Change your code to:

class Test:
    def __init__(self):
        self.field = [(1,2)]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 6
    Unless he overrides `__copy__`/`__deepcopy__`. Still though, that would be pretty odd. – Silas Ray Aug 21 '13 at 17:50
  • 1
    This is actually not an answer to the question, but a workaround to the problem. If you dont want to/cant instantiate the class in every case, e.g.: you have a `@classmethod`, you cannot apply this workaround... – Vajk Hermecz Feb 13 '14 at 11:12
0

Another approach with python 3.8 (I am not sure about previous versions) could be creating a __init__ method that deep-copies every class level attribute, like:

from copy import deepcopy

class Test:
    field = [(1,2)]
    def __init__(self):
        for attr in dir(self):
            if not attr.startswith('_'):
                setattr(self, attr, deepcopy(getattr(self, attr)))

t1 = Test()
t2 = deepcopy(t1)

t2.field[0]=(5,10)

print(t1.field) # [(1,2)]
print(t2.field) # [(5,10)]

of course you can also replace the dir with inspect.getmembers.

Danton Sá
  • 13
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 19 '23 at 17:12