__dict__ is neato torpedo!

Andrew Berg bahamutzero8825 at gmail.com
Sun Jun 12 00:32:15 EDT 2011


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.
> You can create a new dict or a new list by feeding the
> esiting one to the constructor for the type.
Not sure what you mean here. I thought you meant it copies a dictionary
when used as input in an __init__() method, but I tried that in the
interpreter and a still affects b:

>>> class testObj():
...     def __init__(self,input):
...             self.__dict__.update(input)
...
>>> a = dict(list=['one', 'two'], str='hello')
>>> b = testObj(a)
>>> a['list'].append('three')
>>> a
{'list': ['one', 'two', 'three'], 'str': 'hello'}
>>> b.list
['one', 'two', 'three']
>  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".
> Be aware, though, that most Python code gets by just fine without
> explicitly making copies, and I hardly ever see the ‘copy’ module
> actually used.
Now that I think about it, I could probably restrict myself to immutable
types inside the dictionary without much problem. Was that your point,
or did you mean something else?



More information about the Python-list mailing list