By value or by reference?

Bruno Desthuilliers bdesth.quelquechose at
Tue Oct 19 19:06:08 CEST 2004

Donn Cave wrote:
> In article <4173eed0$0$29488$636a15ce at>,
>  Bruno Desthuilliers <bdesth.quelquechose at> wrote:
> ...
>>*Short answer :*
>>args are passed by ref, but bindings are local.
>>*Long answer :*
>>You first need to understand what 'variables' in Python are. They are in 
>>fact just a symbol referencing an object. Think of a Python 'variable' 
>>as an entry in a dict, the name of the variable (the 'symbol') being the 
>>key and the reference to the object being the value (AFAIK, this is 
>>exactly what they are).
>>You also need to understand the difference between mutable and immutable 
>>objects. Strings, numerics and tuples are immutables. Which means that 
>>you can not change them. When doing :
>>s = "Hello "
>>s += "World"
>>... you are not modifying the string object bound to s, but creating a 
>>new string object and binding it to s.
> Well, true enough for string, but not true for list for example.

I may not have made clear enough that this consideration only applied to 
immutable objects...

> Aside from this wretched wart on the language, as another followup
> has already pointed out, you really don't need to distinguish
> mutable vs. immutable to understand argument passing and variable
> binding in Python.
> If you write:
>   def f(a, b):
>       a = 5
>       b.flog(5)
> ... it makes no difference whether either argument is mutable
> or immutable.  a becomes a different object notwithstanding,
> and b.flog operates on the caller's original object whether flog
> modifies anything or not.  We tend to make this too complicated.

Perhaps, but still there's the case of

def foo_list(bar_list):
   bar_list += ['42']

which behave quite differently from

def foo_str(bar_str):
   bar_str += '42'

My 2 cents

More information about the Python-list mailing list