On Mon, Feb 2, 2009 at 10:02 PM, Ferdinand Sousa <ferdinandso...@gmail.com> wrote: > Hi > > Some weeks back I had been following the thread "Why can't assign to > function call". Today, I saw the "function scope" thread, and decided I > should ask about the behaviour below: > >>>> # >>>> Simple variables >>>>p=55 >>>> q=p >>>> q > 55 >>>> q=44 >>>> p > 55 >>>> >>>> # >>>> In a function >>>> def dd(d): > del d['key'] > return d > >>>> adict={'pramod':'goodboy', 'ferdi':'badboy', 'key':'to be deleted'} >>>> dd(adict) > {'ferdi': 'badboy', 'pramod': 'goodboy'} >>>> adict > {'ferdi': 'badboy', 'pramod': 'goodboy'} # > undesirable? >>>> >>>> # >>>> In a class >>>>class AA: > a=111 > > >>>> x=AA() >>>> x.a > 111 >>>> y=x >>>> y.a > 111 >>>> y.a=222 >>>> x.a > 222 # > undesirable? >>>> z=copy.deepcopy(x) >>>> z.a > 222 >>>> z.a=444 >>>> x.a > 222 >>>> y.a > 222 >>>> > > Guess the simple types show the expected behaviour (even though they are > technically instances of existing classes). The user defined classes seem to > be references/shallow copies. The "function scope" thread refers to > http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects > to explain why default parameters should not be modified. But, in the > function example above, the dictionary passed as a variable *in the calling > scope* gets modified. > > How can you avoid the dictionary being changed? > Assigning one object to another always creates references? Can you modify > anything in the class def to get a copy? [I have a tingling feeling this is > how the default types (integers, strings etc) are defined]
Stephen gave a great summary of the issue; here's another popular write-up about it: http://effbot.org/zone/call-by-object.htm Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list