Re: scared about refrences...




Marc 'BlackJack' Rintsch wrote:
In <1162236136.367603.165180@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>, SpreadTooThin
wrote:

I'm really worried that python may is doing some things I wasn't
expecting... but lets see...

Expect that Python never copies something if don't ask explicitly for a
copy.

if I pass a list to a function def fn(myList):

and in that function I modify an element in the list, then does the
callers list get modied as well.

def fn(list):
list[1] = 0

myList = [1, 2, 3]
print myList
fn(myList)
print myList

[1,2,3]
[1,0,3]

How can I avoid this? In this case this is a really simplified example
but the effects are the same...

In this case:

def fn(lst):
lst = list(lst)
lst[1] = 0


How do I specify or create deep copies of objects that may contain
other objects that may contain other object that may contain other
objects....

See the `copy` module especially `copy.deepcopy()`.


This appears to be the right thing to do to me.. (but what do I know?)
I tried this which more closely resembles my project but this doesn't
work:

import array
import copy

class test:
def __init__(self):
self.a = array.array('H', [1, 2, 3])
self.b = ['a', 'b', 'c']

def dump(self):
print self.a, self.b

t = test()
t.dump()

def testit(x):
t = copy.deepcopy(x)
t.a[1] = 0
t.b[1] = 0

testit(t)

t.dump()

.



Relevant Pages

  • Re: scared about refrences...
    ... expecting... ... Expect that Python never copies something if don't ask explicitly for a ... and in that function I modify an element in the list, ... def fn: ...
    (comp.lang.python)
  • Re: Wrapping method calls with metaclasses
    ... > recipe and your definition of class Test, w/Python 2.4.2 on Mac OS 10.4. ... It seemed that the problem arose because I was not using super() in a new ... def test: ... In my project I'm doing deeply nested recursion things and it exceeds the ...
    (comp.lang.python)
  • Re: Method overloading?
    ... Is it possible to be able to do the following in Python? ... def puts: ... when the arg doesn't conform - if the user sends invalid args, ...
    (comp.lang.python)
  • Re: Undefined Method confusion - Ruby Newbie (I know it rhym
    ... Project Euler, ... def series ... The 'for' loop is executing in the context of the class definition, ...
    (comp.lang.ruby)
  • catching exceptions
    ... Hi, In the following program, I have a class Test which has a property ... def _setx: ... based one, and in the calling side, If I have gui, I will pop-up a ... leave the entire thing to the caller (software people call this ...
    (comp.lang.python)