Empty list as default parameter

Robin Munn rmunn at pobox.com
Fri Nov 21 10:59:01 EST 2003


Alex Panayotopoulos <A.Panayotopoulos at sms.ed.ac.uk> wrote:
> On Fri, 21 Nov 2003, anton muhin wrote:
>
>> Really common mistake: lists are _mutable_ objects and self.myList 
>> references the same object as the default parameter. Therefore 
>> a.myList.append modifies default value as well.
>
> It does?!
> Ah, I've found it: listHolder.__init__.func_defaults
>
> Hmm... this behaviour is *very* counter-intuitive. I expect that if I were 
> to define a default to an explicit object...
>
> 	def process_tree1( start=rootNode )
>
> ...then I should indeed be able to process rootNode through manipulating 
> start. However, if I define a default as a new instance of an object...
>
> 	def process_tree2( myTree=tree() )
>
> ...then the function should, IMHO, create a new object every time it is 
> entered. (By having func_defaults point to tree.__init__, or summat.)
>
> Was there any reason that this sort of behaviour was not implemented?

The reason for this behavior lies in the fact that Python is an
interpreted language, and that the class and def keywords are actually
considered statements. One creates a class object with a certain name,
the other creates a function object with a certain name. The def (or
class) statement is executed as soon as the entire function code or
class code has been parsed -- in other words, as soon as the interpreter
drops out of the indentation block of the def or class statement.
Therefore, any default values passed to function arguments in a def
statement will be evaluated once and only once, when the def statement
is executed.

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.

-- 
Robin Munn
rmunn at pobox.com




More information about the Python-list mailing list