How does Python (v2.1.1) handle parameter passing? By value or by reference?

Jeff Shannon jeff at ccvcorp.com
Wed Aug 22 18:59:42 EDT 2001


Rob van Wees wrote:

> Hi all,
>
> As a newbie to Python, I'm having trouble finding out how the interpreter
> handles parameters that are passed to functions. Sometimes they seem to be
> handled as values and sometimes as references.
>

The standard answer is that Python always uses call-by-value, but the values
that it passes are references.

When you pass a parameter into a function, you have a *new* reference to the
object that the parameter is pointing to.  If you then rebind that reference (as
you do in f1 and f3), you have not affected the original object; the original
references to that object are unaffected as well.  However, if you *mutate* the
object that the reference is pointing to (as you do in f2), then all other
references to that object still point to the same, mutated object.  The key
difference is whether your function modifies the original object, or creates a
new (though perhaps related) object.  Try playing around with the id() function
(which returns the unique ID of any python object) to get a better feel for
what's happening under the covers.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list