News for hackers. Stuff that matters.
Re:Python best practices by aston on Tuesday July 08, 2008 @08:07PM (#240557)
Though I am a lowly Python noob, I'll tell you it's generally very bad practice to use a mutable as a default argument value. The reason is that a function's default is only ever initialized once. Case in point:

  >>> def f(l=[]):
  ...     l.append(0)
  ...     print l
  ... 
  >>> f()
  [0]
  >>> f()
  [0, 0]
  >>> f()
  [0, 0, 0]
Unless you 1) actually want the appearance of a 'static' local variable or 2) are really careful to make a copy of the mutable before messing around with it, you'll get yourself into trouble.
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.