2

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

I made this function:

def test(num,v=[]):
    v.append(num)
    if num == 10:
        return v
    return test(num+1,v)

When I use it, the result of previous calls seems to still be there:

>>> test(3)
[3, 4, 5, 6, 7, 8, 9, 10]
>>> test(3)
[3, 4, 5, 6, 7, 8, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10]
>>> test(3)
[3, 4, 5, 6, 7, 8, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10]

If I use just v in the function declaration as opposed to v=[], it seems to work.
What am I missing? I want the function to be fresh each time I run it. I use Python 2.7.3.

Community
  • 1
  • 1

1 Answers1

2

When you use an object as a default argument the same instance of the object is used for all calls to that function. This works fine for immutable objects but becomes a problem for mutable objects. The same object is modified and reused multiple times when the function probably expects to have a "new" object.

You can use a workaround like this to get the functionality you want:

def test(num,v=None):
    if v is None:
        v = []
    ....
Tim
  • 11,710
  • 4
  • 42
  • 43
  • 1
    While your first sentence is true as written, to be clear, the same instances are also used for immutable objects like integers and strings. IOW it's not a mutability issue per se. – DSM Nov 18 '12 at 03:07
  • Thanks. Wow, that's very unintuitive, I've been using python for ~2 years and have no idea it works this way. – user1832924 Nov 18 '12 at 03:08
  • @DSM: good point, but the mutability is what makes it an issue – Tim Nov 18 '12 at 03:15
  • 1
    @Tim: sure, but if you think of it as "mutable objects behave differently from immutable ones" it seems like an unintuitive quirk. If you think of the arguments as part of the `def`, and not part of the function, it makes perfect sense why Python acts as it does. – DSM Nov 18 '12 at 03:29