Lists & "pointers"

Kay Schluehr kay.schluehr at gmx.net
Sat Jul 23 21:03:56 CEST 2005


Jan Danielsson wrote:
> Hello all,
>
>    I have written a simple whiteboard application. In my application, I
> want to be able to set draw attributes. This part works. I have a
> dictionary object which contains stuff like:
> self.attr['Pen.Color'] = ...
> self.attr['Pen.Thickness'] = ...
>
>    Now, the problem is that I want to be able to store attributes in a
> list so they'll be easily accessed using the function keys. I.e. I have
> the "current attributes" which I want to be able to store or retrieve
> in/from a list,
>
> The problem is that I have initialized the list like this:
>
> self.drawAttr = { blah, blah, blah.. }
> self.storedAttr = [ ]
> for i in range(0, 10):
>    self.storedAttr.append(self.drawAttr)
>
>    I know what the problem is; they are all referencing the *same*
> dictionary object. So, my question is: How do I initialize a list of
> dictionary objects, where each list entry is its own object (which is a
> copy from the self.drawAttr object).

Hi Jan son of Daniel,

you might initialize self.storedAttr with empty dicts and fill them
later:

self.soredAttr = [{}]*10
for entry in self.storedAttr:
    entry.update(self.drawAttr)


> Also, how do I store/restore entries to the list?
>
>    I have found the "copy" module, and it's copy method. I assume this
> would work:
>
> for i in range(0, 10):
>    self.storedAttr.append(copy.copy(self.drawAttr))
>
>    However, the concept of "deep copy" confuses me. Do I want it, or
> don't I want it? I repeat: the attributes object is a simple dictionary.
>
> Thankful for any advice.

A *shallow copy* creates a new dictionary and copies the references, a
*deep copy* tries to create a new reference for each existing object in
the dict. The disadvantage of deepcopy is that it does not work in many
cases:

>>> copy.deepcopy([lambda :None])
Traceback (most recent call last):
...
TypeError: function() takes at least 2 arguments (0 given)

As the docs tell:

"This version does not copy types like module, class, function, method,
stack trace, stack frame, file, socket, window, array, or any similar
types."

I wonder if one couldn't pickle a module and reimport it in order to
create a copy of it ;)

IMO this is a weakness of the algorithm. One usually doesn't want to
duplicate a function so that a new reference of a function is not
needed because it is readonly and the algorithm could reuse the same
reference. For classes I don't if the assertion in the docs is actually
true?

>>> class A:pass
>>> copy.deepcopy(A)
<class __main__.A at 0x01191990>

>>> class A(object):
... 	def __init__(self):pass
... 
>>> copy.deepcopy(A)
<class '__main__.A'>
>>> 

Regards,
Kay




More information about the Python-list mailing list