Default function arguments behaving badly

Paul McNett p at ulmcnett.com
Wed Aug 24 12:01:18 EDT 2005


jonny.longrigg at gmail.com wrote:

> I'm having some trouble with a function I've written in Python:

> def myFunction(l1,l2,result=[]):
[snipped rest of function and explanation of what it does]

> Does anyone know what is going on here? Is there an easy solution?

It shined out like a supernova. It has to do with mutability of certain 
Python objects (e.g. dicts and lists) and the fact that Python binds the 
default arguments only once. So, when your function is defined, python 
binds the name "result" to the value []. Then, your function runs the 
first time using that original binding. The second time, it still uses 
the original binding which, because lists are mutable, still contains 
the prior list. Etcetera.

The solution is to never assign mutable objects to default arguments. 
Instead, assign to None, like:

def myFunction(l1, l2, result=None):
	if result is None:
		result = []

Others will certainly post links to the python docs that explain this.

-- 
Paul McNett
http://paulmcnett.com




More information about the Python-list mailing list