Parameters passing in Python

Alex Martelli aleax at aleax.it
Mon Nov 3 05:15:38 EST 2003


kk wrote:

> When I learnt Java, I was told that for its primitive types, parameter
> passing is done by value. For objects, by reference.

With Python, always "by object reference".  Of course, for immutable
types (strings, numbers) it makes no real difference!

> I started to learn Python months ago, but I still can't figure out the
> parameter passing style of Python. List, Dict, Object...
> When I search in mailing list, I found that someone raised the same
> question and someone responded Python uses 'pass by object'.
> Would anyone explain a bit more in detail?

Just like in Java to all intents and purposes.  You get a reference
to the object (NOT to the name, aka variable, that may refer to that
object).  If the object is immutable (string, number, tuple) that's
just like receiving a copy of the value -- there is no copy -- it's
the original value -- but you don't care since nothing can change it
anyway.  If the object is mutable (list, dict, instances of most
usercoded classes) then it IS important that no copy is implicitly
made (just as no copy is implicitly made in java) since you can
mutate the object (append to a list, etc etc) and what will be
mutated is "the original" that was passed.  If you WANT a copy you
explicitly ask for one (most generally via standard module copy).


Alex





More information about the Python-list mailing list