Issue using deepcopy with dictionary inside object

Reading the documentation, I understood that copy.deepcopy(obj) copies recursively any other object inside this one, but when I run:

>>> import copy
>>> class SomeObject:
...     a=1
...     b={1:1,2:2}
... 
>>> o1=SomeObject()
>>> o2=copy.deepcopy(o1)
>>> id(o1)
140041523635624
>>> id(o2)
140041523635912
>>> id(o1.b)
30087968
>>> id(o2.b)
30087968

It does not seem to be copying the dictionary inside 'o1'. Can anyone tell me if I am doing something wrong, or how can I get a copy of the dictionary inside the object?

Thanks

Answers


Deepcopy only copies instance attributes. Your b attribute is a class attribute, instead.

Even if you did not create a copy but a new instance of SomeObject manually, b would still be shared:

>>> class SomeObject:
...     a=1
...     b={1:1,2:2}
... 
>>> so1 = SomeObject()
>>> so2 = SomeObject()
>>> so1.b is so2.b
True
>>> so1.b is SomeObject.b
True

Make b an instance attribute:

>>> import copy
>>> class SomeObject:
...     a = 1
...     def __init__(self):
...         self.b = {1: 1, 2: 2}
... 
>>> so1 = SomeObject()
>>> so2 = copy.deepcopy(so1)
>>> so1.b is so2.b
False

Need Your Help

Blur background content on pop up?

jquery popup shadowbox

SO this is more of a "is this possible" kind of question rather than "how can I fix my idiot errors?" sort of thing.