You could, however, argue that the swap function doesn't work as
expected (e.g. from a Pascal or a C++ POV) simply because the
underlying objects aren't mutable.
That's irrelevant - mutable and immutable objects are passed exactly the
same way.
The objects *do* get passed by
reference; the function doesn't receive a new copy of the object and
it can examine the original object's ID. The actual culprit is not the
way objects are passed but the assignment operator, since it works by
rebinding names (as Andrew Koenig explained) and not by changing the
object itself.
There is *no* difference between "the way objects are passed" and "the
assignment opera[tion]": both work exactly the same way.
Python execution model is based on namespaces (a collection of
name->object pairs, usually implemented as dictionaries). An assignment x
= y means:
- evaluate the right hand side and obtain a value (an object, always). In
this case, it is the object referenced by the name "y"
- make the name "x" refer to such object. That's all.
In short, assignment rebinds a name in a namespace.
When a function call is made, a new namespace is created. The names come
from the function parameters (the names that were used to define the
function in the def ... line) and the objects come from the actual
arguments (the objects you pass inside the (...) when doing the call). The
function code is then executed using this namespace as its locals().
def foo(a, b):
print a, b
foo(4, ['hello', 'world!'])
The call is equivalent to:
ns = {}
ns['a'], ns['b'] = 4, ['hello', 'world!']
execute foo code using ns as locals
except the right hand side is evaluated on the *calling* namespace, and
the left hand assignments are done on the new namespace. So a call binds
many names in a new namespace: the same as assignment.
No copies, no pointers, nothing: only names and objects are manipulated.
If the swap() function could somehow access the
underlying integer object and modify it, swapping of values would
indeed occur because the function *did* get references to the objects
passed to it.
There is a difference between modify the value of an object, and modify
the caller's namespace. Usually "pass by reference" means that the
*caller* may see a different thing after the call - this is not true in
Python, there is no way the called code could alter the caller namespace
(well, not just due to the call operation alone...)
That said, it's a rather convoluted way of explaining what happens and
calling it pass-by-object feels much better.
And is more correct...