__dict__ is neato torpedo!

Ian Kelly ian.g.kelly at gmail.com
Sun Jun 12 01:12:54 EDT 2011


On Sat, Jun 11, 2011 at 10:32 PM, Andrew Berg <bahamutzero8825 at gmail.com> wrote:
> On 2011.06.11 10:40 PM, Ben Finney wrote:
>> It's exactly the same as with an ordinary assignment (‘a = b’) in
>> Python.
> Fair enough.
>> > How would I make actual copies?
>> At what level?
> Level? I just want to be able to create an object b with values from
> dictionary a, and not have changes to a reflect b and vice-versa once b
> is created.

It sounds like the copy.deepcopy function is what you want:

>>> from copy import deepcopy
>>> class X(object): pass
...
>>> a = X()
>>> a.fruit = ['apples']
>>> b = deepcopy(a)
>>> a.fruit
['apples']
>>> b.fruit
['apples']
>>> a.fruit.append('oranges')
>>> a.fruit
['apples', 'oranges']
>>> b.fruit
['apples']


>>  Or you can use the various
>> methods in the ‘copy’ module depending on what you want.
> copy.deepcopy() looks appealing, but I don't know what the docs mean by
> "administrative data structures".

It just means that you don't always want absolutely everything copied.
 For example:

>>> class World(object): pass
...
>>> class Actor(object):
...     def __init__(self, world):
...         self.world = world
...
>>> class Action(object):
...     def __init__(self, actor):
...         self.actor = actor
...
>>> a = Action(Actor(World()))
>>> b = deepcopy(a)
>>> a.actor is b.actor
False
>>> a.actor.world is b.actor.world
False

The intention here is probably that a and b should both be part of the
same World, but as you can see that is not the case; the World got
copied along with everything else.  Python provides machinery to let
you avoid deep copying absolutely everything, but it's important to be
aware of cases like this.

Cheers,
Ian



More information about the Python-list mailing list