Using dicts and lists as default arguments of functions
MRAB
python at mrabarnett.plus.com
Mon Aug 9 11:35:50 EDT 2010
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['1'] = 1
print 2, a
def tstb(a=None):
if a is None:
a = []
print 1, a
a.append(1)
print 2, a
It's all explained here:
http://effbot.org/zone/default-values.htm
More information about the Python-list
mailing list