2

I have difficutly understanding an example from a book (Introducing Python).

First related example which I do understand:

 >>>def buggy(arg, result=[]):
 ...    result.append(arg)
 ...    print(result)
 ...
 >>buggy('a')
 ['a']
 >>>buggy('b')
 ['a', 'b']

The example above illustrates that default argument values are calculated when the function is defined, not when it is run. This make sense to me.

The next example shows how to avoid the issue. It works, but I do not understand how.

>>>def nonbuggy(arg, result=None):
...    if result is None:
...        result = []
...    result.append(arg)
...    print(result)
...
>>>nonbuggy('a')
['a']
>>>nonbuggy('b')
['b']

My understanding (obviously wrong) is that when it is run for the first time, the result is None, therefore result = [] should be executed and 'a' appended.

When run for the second time, result is not None (it is 'a'), so only 'b' should be appended and so I expect ['a', 'b'] to be returned. But I get only ['b'] exactly as it is in the book.

Please could you advise how it is possible?

  • 1
    You *rebind* `result` in the function. When the function is called, the `result` local is bound to the default object `None`. You then rebind it to refer to an empty list instead. The default stored in the function is no longer referenced by `result`, but it isn't itself altered. – Martijn Pieters May 07 '14 at 12:15
  • Martijn, now I understand. Thank you very much! – Jiri Mensik May 07 '14 at 15:49

0 Answers0