News for hackers. Stuff that matters.
Re:Python best practices by nostrademons on Wednesday July 09, 2008 @11:37AM (#241262)
I always took that as a case against mutating arguments, not against defaults. You still have the same problem if you pass in an argument:

>>> MY_CONSTANT = ['foo', 'bar', 'baz'] >>> def f(l): ... l.append(0) ... print l ... >>> f() ['foo', 'bar', 'baz', 0] >>> f() ['foo', 'bar', 'baz', 0, 0]

I would've rewritten f as:

  def f(l=[]):
      print l + [0]
...unless you specifically want f to mutate its caller's variables and have documented it as such.

Generally, I try to avoid mutating objects unless a.) I just created the object within the function or b.) it's specifically intended as a "long lived" data structure, i.e. something that survives multiple user interactions. For everything else, I try to use the non-mutating operations (slicing, concatenation, list comprehensions) or make an explicit copy of the argument.

There are no comments on this comment yet.