problem calling functions with default arguments

Russell E. Owen owen at astrono.junkwashington.emu
Wed Aug 15 14:16:06 EDT 2001


Consider the following code:

def atest(alist = []):
  print "alist =", alist
  alist.append("test")

atest()
atest()
atest()

I was expecting that alist would be empty every time it is printed. 
However, when I run the code I see:

alist = []
alist = ['test']
alist = ['test', 'test']

It appears that alist is persisting in the function. Is there some 
standard easy way to work around this, so that:
- if the caller specifies an argument, it is used
- if the user does not specify an argument, the default specified in the 
argument list is used

So far I've thought of two possibilities, neither at all attractive:
- Never use a default for a container (list, dictionary...)
- Always reset the container to the desired default state when finished, 
a process rife with potential errors (making sure it always gets set and 
making sure the final set value stays in synch with the default value)

I have seen this on Python version 2.1.1 on a Mac and Python version 2.0 
on Solaris, so it's clearly been around for awhile. I'm amazed I only 
stumbled across it today (trying to debug some truly bizarre behavior in 
my Tk GUI application, due to assuming a dictionary would default to {} 
as specified).

-- Russell



More information about the Python-list mailing list