0

The following python code:

def test_function(a = []):
    a.append('x')
    print(a)

test_function()
test_function()

prints:

['x']
['x', 'x']

It seems like the a=[] default assignment is only used once, after which a is treated as a property of the function unless it is reassigned when the function is called again (e.g test_function(a=['hello'])). The behaviour is shared between Python2.x and 3.x so I assume it is not perceived as a design flaw.

I'd like to know:

  1. What is the mechanism for this behaviour?
  2. What is the rationale behind this behaviour? (it seems confusing to me)
Mike Vella
  • 10,187
  • 14
  • 59
  • 86

1 Answers1

1

The default value is an expression, which is evaluated only once at the moment the function is defined/compiled. It is probably stored somewhere in the function-object, so when this expression evaluates to a mutable object like a list, you get the effect you described. I don't know about the rational for this, but it is a feature of python.

In [11]: def f(x = [], y = 123):
    ...:     pass

In [12]: f.func_defaults
Out[12]: ([], 123)
Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62