By value or by reference?

Donn Cave donn at u.washington.edu
Mon Oct 18 15:42:47 EDT 2004


In article <4173eed0$0$29488$636a15ce at news.free.fr>,
 Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> 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.

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.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list