Using dicts and lists as default arguments of functions

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Aug 9 11:34:23 EDT 2010


Johan a écrit :
> Dear all,
> 
> Considering this test program:
> 
> def tst(a={}):

Stop here, we already know what will follow !-)

And yes, it's one of Python's most (in)famous gotchas : default 
arguments values are computed only once, at function definition time 
(that is, when the def statement is executed).

The correct way to write a function with mutable default arguments is:

def func(arg=None):
    if arg is None:
        arg = []
    # then proceed

HTH



More information about the Python-list mailing list