initialization in argument definitions

Terry Reedy tjreedy at udel.edu
Fri Nov 21 17:41:35 EST 2008


Brentt wrote:
> Hi, I know this is a terribly simple question, but the docs seem to be
> designed for people who probably find a the answer to this question
> terribly obvious. But its not at all obvious to me.
> 
> I can't figure out why when I define a function, a variable
> (specifically a list) that I define and initialize in the argument
> definitions, will not initialize itself every time its called. So for
> example, when making a simple list of a counting sequence from num (a
> range list), if I call the function multiple times, it appends the
> elements to the list generated the times it was called before, even
> though the variable for the list is initialized in the argument
> definitions.
> 
> def foo_range(num,aList = []):
> aList = []
> #why is this seemingly extra initialization necessary? shouldn't it be
> initialized in the argument definitions?
> #but if its not there and the function is called multiple times the
> elements generated (see below)
> #append to the list generated before.
> while num <= 10:
> aList.append(num)
> num +=1
> else:
> return aList
> 
> Why is this? Thanks, hope its not a stupid quesiton.

The def statement is an executable statement that creates a function 
object.  When you execute the def statement, the parameter list, 
including default arg object expressions, is evaluated for creating the 
function object and its associated code object.  The 'suite' that 
follows the ':' and possible a doc string is compiled for the code object.

The language manual entry for Function definitions explains this, with 
the first sentence in bold.
"Default parameter values are evaluated when the function definition is 
executed. This means that the expression is evaluated once, when the 
function is defined, and that that same “pre-computed” value is used for 
each call. This is especially important to understand when a default 
parameter is a mutable object, such as a list or a dictionary: if the 
function modifies the object (e.g. by appending an item to a list), the 
default value is in effect modified."

The allows a choice of having a 'default' evaluated either when the 
function is defined, which is nearly always what is wanted, or when the 
function is called, by using None or another flag object, and then testing.

tjr




More information about the Python-list mailing list