Varibles -- copies and references

Terry Reedy tjreedy at udel.edu
Tue Feb 3 10:34:30 CET 2009


Ferdinand Sousa 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

You both mutated and returned the input object.  This is undesirable.
All built-in functions and methods that mutate an object have a verb for 
a name and return nothing.  (Ok, find an exception if you can, but that 
is the intented convention.)  Statements, of course, also have no 
'return'.  So either

def strip_key(d):
   del d['key']
# or
def stripped_of_key(d):
   newd = dict(d)
   del newd['key']
   return newd

tjr




More information about the Python-list mailing list