[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Concerning copy



In a message of Sat, 22 Apr 2006 21:56:34 PDT, Nelson writes:
>--0-893589239-1145768194=:75000
>Content-Type: text/plain; charset=iso-8859-1
>Content-Transfer-Encoding: 8bit
>
>Python's does pass by value, but the object is reference and if you modif
>y it via a method it should be changed forever.
>
>>From http://www.poromenos.org/tutorials/python:
>
>def func(arg):
>    arg = ['another value']
>
>value = ['original value']
>func(value)
>print value
>['original value']
>
>def func(arg):
>    arg.append("value added by func")
>
>value = ['original value']
>func(value)
>print value
>['original value', 'value added by func']
>
>Languages rarely have the ability to turn off "features" - akin to tellin
>g the English language not to have pronouns.
>
>Nelson
>http://www.tojam.ca
>
>Kevin Turner <darian@xxxxxxxxxxxxx> wrote: Recently I encountered an issu
>e where Python would, instead of creating 
>a new object, instead reference the original one. Using copy.copy() is 
>a solution, but I'd much rather be able to toggle off the weird 
>referencing that Python has been using and make exceptions as 
>necessary. Is there any way to do this?

This problem has to do with the fact that lists are mutable.  Indeed
because copy.copy(mylist) only makes a shallow copy of a list, you may
need copy.deepcopy() to get what you want.

>>> import copy
>>> c = [1, 2, 3, [4, [5, 6]], 7]
>>> ccopy = copy.copy(c)
>>> cdeepcopy = copy.deepcopy(c)
>>> c
[1, 2, 3, [4, [5, 6]], 7]
>>> ccopy
[1, 2, 3, [4, [5, 6]], 7]
>>> cdeepcopy
[1, 2, 3, [4, [5, 6]], 7]
>>> c[3][0] = 'elephant'
>>> c
[1, 2, 3, ['elephant', [5, 6]], 7]
>>> ccopy
[1, 2, 3, ['elephant', [5, 6]], 7] # perhaps this will surprise you
>>> cdeepcopy
[1, 2, 3, [4, [5, 6]], 7]
>>>   

If what you want is an immutable sequence, then python already has
the datatype you want, called a tuple.  Since tuples are immutable,
you cannot modify them in place, but instead have to copy them.
They look like lists except with round brackets not square ones.

(1, 2, 3, (4, (5, 6)), 7)

Tuples of size one element have to have a trailing ',' 

>>> (1)   # I am not a tuple.  I will get evaluated.
1
>>> (1,)  # I'm a tuple
(1,)

If your lists are flat you can use the tuple function to convert them to
tuples:

>>> tuple([1,2,3,4])
(1, 2, 3, 4)

but tuple only works on the outer level:
>>> tuple(c)
(1, 2, 3, ['elephant', [5, 6]], 7)

Note: there is a reason that python has both mutable and immutable
sequences.  All this copying takes time.  So using an immutable datatype
may impose an unacceptable performance penalty for you.

Laura