Something in the function tutorial confused me.

Neil Cerutti horpner at yahoo.com
Mon Aug 6 07:25:22 EDT 2007


On 2007-08-06, Lee Fleming <countblabula at yahoo.com> wrote:
> I have a simple question. Say you have the following function:
>
> def f(x, y = []):
>     y.append(x)
>     return y
>
> print f(23)  # prints [23]
> print f(42)  # prints [23, 42]
>
> def  f(x, y=None):
>     if y is None: y = []
>     y.append(x)
>     return y
>
> print f(23)  # prints [23]
> print f(42)  # prints [42]

Default argument expressions are evaluated only once,
specifically, at the time the function definition is executed.

Statements inside the function are executed every time the
function is called.

> Why didn't the second call to f, f(42) return [23, 42]?

Because when the function is called,  the line

>     if y is None: y = []

is executed, binding a brand new empty list to y. This
"rebinding" happens every time the function is called, unless you
provide an argument for y that is not None.

For example, with the second definition...

 >>> f(f(23))
 [23, 42]

See:

http://www.ferg.org/projects/python_gotchas.html#contents_item_6

This has been called a gotcha for a good reason. The sequence of
events for the binding of default arguments isn't obvious, and
for expressions that result in mutable objects, it's not
intuitive.

-- 
Neil Cerutti
The outreach committee has enlisted 25 visitors to make calls on people who
are not afflicted with any church. --Church Bulletin Blooper



More information about the Python-list mailing list