By value or by reference?

Alex Martelli aleaxit at yahoo.com
Mon Oct 18 16:22:59 EDT 2004


Josiah Carlson <jcarlson at uci.edu> wrote:
   ...
> If what Python does is like Java, perhaps C# or what have you, great.  It
> is, however, different from the C semantic description of "pass by value",
> "pass by reference", and the standard CS education definition of either.

C is also very simple, just like Python: C always does pass by value.
I.e., C always does implicit copy (on assignment or parameter passing),
just like Python never does.

So in C you ask explicitly when you want a reference (pointer) instead,
e.g. with &foo -- in Python you ask explicitly when you want a copy
instead, e.g. with copy.copy(foo).  Two simple language, at opposite
ends of the semantics scale, but each consistent and clean.  (Python
matches 4.5 of the 5 points which define "the spirit of C" according to
the latter's Standard's preface...!-).

[[ok, each has its warts -- e.g. C has arrays which mysteriously decay
into pointers instead of getting copied, Python has slices that make
copies instead of sharing part of the original sequence [or not; it
depends whether said sequence is a list or Numeric.array, sigh...] --
being human and being perfect are incompatible traits.  But _mostly_
they have simplicity and consistency, everything explicit.]]

The key point is that, in both languages, a function's arguments are
just like local variables pre-initialized by the caller with assignment
statements.  In both languages, if the function reassigns an argument
it's just playing with its own local variables, the caller is never in
any way affected by that.  In both languages, there are other ways
except plain barename assignments to possibly "affect the caller" (in C
you basically need to have been passed a pointer, and dereference that
pointer or another pointer computed from the first by pointer
arithmetic; in Python you basically need to have been passed a mutable
object, and call mutating methods on that object).  Again, in both cases
I see simplicity and consistency, everything pretty explicit...


Alex



More information about the Python-list mailing list