Tuesday, February 2, 2016

Tricky questions: function parameters with default mutable values

Today I discovered one confusing feature of Python. And also decided to open new category on my blog, which will be called "tricky python questions".

def append(num, to=[]):
    return to

aa = append(1)
print aa

bb = append(2)
print bb

We just call a function which default value should be initialized to an empty list, so the final output is supposed to be:

But that's wrong answer. Python will output this:
[1, 2,]

The reason of that is that mutable default value can be modified! What I mean is that 'default' value for mutable type is not fixed anymore. If we mutate mutable parameter, its default value is also mutated and saved in the function's scope until next call.

No comments:

Post a Comment