2

Please take a gander at this function with a mutable object list as a default argument:

def foo(x, items = []):
    items.append(x)
    return items
foo(1)      #returns [1]
foo(2)      #returns [1,2]
foo(3)      #returns [1,2,3]

I am curious as to why does this happen? I mean I have read that a function's scope is terminated as soon as it finishes execution, so the items in the first call must have been destroyed after the first call. I then tried to check if the items was in global scope.

>>> print(items)
>>> Traceback (most recent call 
    File "c:\Users\GauriShanker\Desktop\mypython\test.py", line 9, in <module>
    print(items)
    NameError: name 'items' is not defined.

Turns out it is not. I am curious as to :

  1. why was not the items variable destroyed after every call. As is evident clearly, every successive function call is picking the value of the items variable from the last function call. If the items variable is not in global scope, where does it live and why?
  2. When I have not explicitly provided the second arguement in function calls, should it not just make items equal to [] as the default value. Isn't the whole point of declaring the default parameters? It does set items to [] only in the first call but not in the second and third call.

Please guide.

martineau
  • 119,623
  • 25
  • 170
  • 301
Gsbansal10
  • 303
  • 5
  • 12
  • This is almost exactly the same question as the duplicate. Have you read through that yet? – Mateen Ulhaq Dec 01 '18 at 05:55
  • The default parameter objects are attached to the function, so they *don't* get destroyed after the call. Remember that a function is an object too. – Mark Ransom Dec 01 '18 at 05:58
  • 1
    One more thing, objects in Python can have multiple references. You're correct that `items` goes out of scope, but that's only one reference to the object. There's another reference held by the function object so the object itself never gets destroyed. – Mark Ransom Dec 01 '18 at 06:06
  • @MarkRansom I understand that but shouldn't `items` variable be set to `[]` every time I call the function without the second argument? – Gsbansal10 Dec 01 '18 at 06:07
  • 2
    No, because that assignment is only evaluated once, when the function is defined. It isn't evaluated at every function call. – Mark Ransom Dec 01 '18 at 06:08

0 Answers0