Python Newbie

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 22 23:13:52 EST 2013


On Fri, 22 Feb 2013 13:37:20 -0800, piterrr.dolinski wrote:

> Today I learned the hard way that all function parameters in Python are
> passed by reference (meaning whatever happens to them inside a function,
> new values are always passed to caller). Not good.

Today you learned wrong.

This is a common misapprehension. Python is not pass by reference, nor is 
it pass by value. There are many, many more argument passing strategies 
used than just those two. Like Ruby and Java, Python is pass by object-
reference, or pass by sharing if you prefer.

You can read more about this here:

http://www.mail-archive.com/tutor%40python.org/msg46612.html

The canonical test of pass-by-reference is to write a "swap" procedure, 
one which swaps the values of any two variables:

a = 1
b = 2
swap(a, b)
assert a == 2, b == 1


You cannot write this in Python.

The canonical test of pass by value is that arguments are copied when you 
pass them to a function:

a = 1
def different_from_global(argument):
    assert id(argument) != id(a)

different_from_global(a)  # fails


Python does not copy arguments when you pass them to functions.



> I got caught up on
> this. To combat the mostly unwanted behavior, inside a function I have
> to reassign variables intended to be local to new variables. A pain. Can
> anyone offer ONE reason why Python was designed that way?

Because it is a sensible way to operate for an object-oriented language. 
Python will not unnecessarily copy data that doesn't need to be copied. 
If you want a copy, you copy it yourself. On the other hand, function 
parameters should be local to the function. These two requirements rule 
out both pass by value and pass by reference as the parameter passing 
model.


> Out of curiosity, does anyone have any idea why function declarations
> are preceded by the keyword "def" rather than something more intuitive
> like "function" or at least "func", perhaps?

"def" is short for "define". As for why the keyword was chosen to be 
"def" rather than "define" (like Scheme), "function" (like Pascal), 
"defun" (like Lisp), "fun" (like Erland), "define method" (like Dylan), 
or even "swyddogaeth" (Welsh), that's just a matter of personal taste of 
the creator.


-- 
Steven



More information about the Python-list mailing list