0
def a(l=[]):
    print(l)
    l.append('something')

a()     #[]
a()     # ['something']

after a is executed for the first time it seems to be that a's parameter name l and the actual object in heap memory attached to it should be erased from memory because there is nothing in stack memory that refers l 's object in heap memory a is executed so l 's local scope doesn't exist any more and so name l doesn't exist anymore => l cannot refer anything anymore

but empirically I have found that it does not work this way if we write a like this def a(l=[]): and then call it like this a() it seems to be that name 'l' continues to exist even after a is already executed I mean that the object in heap bind to name l continues to exists and stores all alterations caused to it by the first call of a

and when we call a for the second time its first line print(l) prints not empty [] but ['something'] so it seems to be like by the first calling of a we change the a's' code itself from this:

def a(l=[]):
print(l)
l.append('something')

to this

def a(l=['something']):
print(l)
l.append('something')

I thought that if I write a function like this def a(l=[]): every next time I call it like this a() its name parameter written like that foo(name_parameter=[] will be rewritten (or newly created in new 'clear', 'empty' scope) but that's not the case as we can see

my question: how it works? what mechanics is lied behind it?

why in the time when a is not executing and so its entrails names should not exist in memory a's parameters assigned a(HERE) (and not reassigned anywhere else later) nevertheless exist in memory?

Dmitriy Neledva
  • 867
  • 4
  • 10
  • 2
    See ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). – craigb Nov 03 '22 at 06:00
  • you could confirm the prevalence of same object l by printing id(l) in the function. The address may remain the same. – user2685079 Nov 03 '22 at 06:35
  • @user2685079 I know it. And craighb's link explains the problem in full. The explanation was easy to get if we look at this in OOP paradigm: any function is object, and when we call `def a(l=[]):` for the first time data attribute `l` is set to object `a` but when we call it for the subsequent times object `a` already has data attribute `l` so this part `l=[]` of `def a(l=[]):` won't be executed because it's to be executed only of there is no `l` name in `a`'s namespace, but there already is. It has nothing to do with stack names and scopes it's about understanding OOP only. – Dmitriy Neledva Nov 03 '22 at 08:03

0 Answers0