Varibles -- copies and references

Ferdinand Sousa ferdinandsousa at gmail.com
Tue Feb 3 01:02:55 EST 2009


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-objectsto
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]

Thanks and best regards,
Ferdi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090203/c54baa8c/attachment.html>


More information about the Python-list mailing list