0

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

This is very odd, an optional list parameter in Python is persistent between function calls when using the .append() method.

def wtf(some, thing, fields=[]):
    print fields
    if len(fields) == 0:
        fields.append('hey');
    print some, thing, fields

wtf('some', 'thing')
wtf('some', 'thing')

The output:

[]
some thing ['hey']
['hey'] # This should not happen unless the fields value was kept
some thing ['hey']

Why does the "fields" list contain "hey" when it is a parameter? I know it's local scope because I can't access it outside the function, yet the function remembers its value.

Community
  • 1
  • 1
Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96

1 Answers1

3

Default values are only evaluated once, so using a mutable type as a default value will produce unexpected results. You'd do better to do something like this:

def wtf(some, thing, fields = None):
  if fields is None:
    fields = []
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • Note that this won't save you if you ever call `wtf('some', 'thing', something)`. Now `something` has an extra `"hey"` on the end. – Ben Oct 15 '11 at 06:16
  • how so? If "something" were a list, then it would not be None and so the "fields" would equal "something" would it not? – Aram Kocharyan Oct 15 '11 at 07:51