Python default parameters

I was recently bitten by this: “Default parameter values are evaluated when the function definition is executed.” Demo:

def mklist():
  print 'making list'
  return []

def f(x=[]):
  x.append(3)
  print x

print 'start'
f()
f()

The output:

making list
start
[3]
[3, 3]

Annoyingly, the above page from the language reference acknowledges that “This is generally not what was intended,” without justifying the status quo.

Follow me on Twitter for stuff far more interesting than what I blog.