Re: Using dicts and lists as default arguments of functions

2010-08-09 Thread Bruno Desthuilliers
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 e

Re: Using dicts and lists as default arguments of functions

2010-08-09 Thread MRAB
Johan wrote: Dear all, Considering this test program: def tst(a={}): print 1, a a['1'] = 1 print 2, a del a def tstb(a=[]): print 1, a a.append(1) print 2, a del a [snip] Do this instead: def tst(a=None): if a is None: a = {} print 1, a a[

Re: Using dicts and lists as default arguments of functions

2010-08-09 Thread Mel
Johan wrote: > Dear all, > > Considering this test program: > > def tst(a={}): > print 1, a > a['1'] = 1 > print 2, a > del a The idiom to use is def tst (a=None): if a is None: a = {} # ... and so on. This means that every call to tst with unspecified a

Using dicts and lists as default arguments of functions

2010-08-09 Thread Johan
Dear all, Considering this test program: def tst(a={}): print 1, a a['1'] = 1 print 2, a del a def tstb(a=[]): print 1, a a.append(1) print 2, a del a tst() tst() tstb() tstb() With output: t...@tnjx:~/tst> python tt.py 1 {} 2 {'1': 1} 1 {'1': 1} 2 {'1': 1}