always the same object

John Roth newsgroups at jhrothjr.com
Tue Jan 20 19:04:31 EST 2004


"Uwe Mayer" <merkosh at hadiko.de> wrote in message
news:bukbuo$rqp$1 at news.rz.uni-karlsruhe.de...
> Hi,
>
> I am using struct.unpack() quite often. unpack() returns a tuple, however
a
> tuple with always the same id(), which is AFAIK the memory location of the
> structure.
>
> I found myself working with above tuple, initialising other data
structures,
> etc... and when I tried to change one list element, suddenly all list
> elements change => so they all contain the identical object

The biggest problem people have with lists is attempting to
reuse one rather than starting with a new one.

For example, this ***WILL NOT*** work:

class Fubar:
    aList = [None, None, None]

    def addToList(self, something):
        aList[:3] = something

on the other hand, this will work:

class Good:
    def __init__(self):
        self.aList = [None, None, None]

    def addToList(self, something):
        aList[:3] = something


> Now what are the rules when Python re-uses an old object (as with
> struct.unpack() ) and when does it create new objects?

As far as lists are concerned, list literals ([...]) always return a
new list.

> And what ist the proposed solution for dealing with this situation, i.e.
how
> do I create a true copy of what struct.unpack() returns me?

See above.

John Roth
>
> Thanks in advance
> Ciao
> Uwe





More information about the Python-list mailing list