On Fri, 8 May 2015 06:01 pm, Frank Millman wrote: > Hi all > > I have often read about the gotcha regarding 'mutable default arguments' > that frequently trips people up. > > I use them from time to time, but I have never had a problem. I have just > delved a bit deeper to see if I am skating on thin ice. > > AFAICT my usage is safe. If I use a list as an argument, I only use it to > pass values *into* the function, but I never modify the list. So if I omit > the argument, the original default empty list is used, otherwise the list > that I pass in is used. > > However, every time I look at my own code, and I see "def x(y, z=[]): > ....." it looks wrong because I have been conditioned to think of it as > a gotcha.
It is a gotcha, and a code smell. http://www.joelonsoftware.com/articles/Wrong.html You can use it, but with care: code smells aren't necessarily wrong, they just need to be looked at a little more carefully. > Would it be more pythonic to change them all to use the alternative > "z=None", or is it ok to leave it as it is? Or to phrase it differently, > how would an experienced pythonista react on seeing this when reviewing my > code? I would change it to z=None *unless* you actually required the list to be mutated, e.g. if you were using it as a cache. Does z have to be a list? Could you use an empty tuple instead? def x(y, z=()): ... -- Steven -- https://mail.python.org/mailman/listinfo/python-list