Empty list as default parameter

Peter Hansen peter at engcorp.com
Sun Nov 23 15:28:04 CET 2003


Stian Søiland wrote:
> 
> * Robin Munn spake thusly:
> > Look at this, for example:
> >
> >
> >     n = 5
> >     def f(x = n):
> >         return x
> >     n = 3
> >
> >     print n     # Prints 3
> >     print f()   # Prints 5
> >
> > Note that the default argument to f() is the value of n when the def
> > statement was executed, not the value of n when f() is called.
> 
> Wouldn't it be more logical for a programmer that x should evaluate
> to '3' inside f()?
> 
> I can't see what is the purpose of binding default variables at
> definition time instead of runtime.

Purpose?  Who needs a purpose? ... "def" is a *statement* in Python,
so naturally the code in the argument list is mostly easily handled
at definition time, when the def statement is being executed, rather
than at run time.

It also means that the default arguments don't have to be evaluated
dynamically each time the function is called, which would in some
cases be a performance nightmare...

-Peter




More information about the Python-list mailing list