Hi<br><br>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:<br><br>>>> # Simple variables<br>
>>>p=55<br>>>> q=p<br>>>> q<br>55<br>>>> q=44<br>>>> p<br>55<br>>>><br>>>> # In a function<br>
>>> def dd(d):<br> del d['key']<br> return d<br><br>>>> adict={'pramod':'goodboy', 'ferdi':'badboy', 'key':'to be deleted'}<br>>>> dd(adict)<br>
{'ferdi': 'badboy', 'pramod': 'goodboy'}<br>>>> adict <br>{'ferdi': 'badboy', 'pramod': 'goodboy'} # undesirable?<br>>>><br>
>>> # In a class<br>>>>class AA:<br> a=111<br><br> <br>>>> x=AA()<br>>>> x.a<br>111<br>>>> y=x<br>>>> y.a<br>
111<br>>>> y.a=222<br>>>> x.a<br>222 # undesirable?<br>>>> z=copy.deepcopy(x)<br>>>> z.a<br>222<br>>>> z.a=444<br>
>>> x.a<br>222<br>>>> y.a<br>222<br>>>> <br><br>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 <a href="http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects">http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects</a> 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.<br>
<br>How can you avoid the dictionary being changed?<br>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]<br>
<br>Thanks and best regards,<br>Ferdi<br>