mutable default arguments
Arnaud Delobelle
delobelle at blueyonder.co.uk
Thu Feb 27 06:53:40 EST 2003
Hi everyone,
I am an 'amateur' programmer who's recently discovered python, and I
must say it's great. I had this problem though, it took me the
whole morning to understand what it boils down to (I think). So here is
my little piece of code:
def foo(l=[]):
l.append('Spam!')
print ' '.join(l)
for i in range(10): foo()
And now the output (python 2.2.1):
Spam!
Spam! Spam!
Spam! Spam! Spam!
Spam! Spam! Spam! Spam!
Spam! Spam! Spam! Spam! Spam!
Spam! Spam! Spam! Spam! Spam! Spam!
Spam! Spam! Spam! Spam! Spam! Spam! Spam!
Spam! Spam! Spam! Spam! Spam! Spam! Spam! Spam!
Spam! Spam! Spam! Spam! Spam! Spam! Spam! Spam! Spam!
Spam! Spam! Spam! Spam! Spam! Spam! Spam! Spam! Spam! Spam!
Not what I expected (well it is because I made it up just for that, but
not what I would have expected). Of course this is because argument l
defaults to [] which is mutable and obviously the default value is
stored somewhere once and for all, and not (as seemed natural to me)
dynamically recreated each time.
So my question is: what's the rationale behind it? I've spent so much
time working out what the problem was that I have no brainpower left,
sorry.
--
Arnaud Delobelle
delobelle at blueyonder.co.uk
More information about the Python-list
mailing list