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?