Let's say I have the following code in python3:
def func(string):
def wrapper():
print("started")
print(string)
print("Ended")
return wrapper
x = func('string argument')
print(x())
------------------------------- Commentary Below------------------ My output is as follows:
>>started
>>string argument
>>Ended
>>None
Can someone please explain how the line:
print(x())
is still able to access the string argument from the line:
x = func('string argument')
I thought once you pass an agruement into a fun and it runs, that all of the function's variable are cleared out. Is this considered the topic of garbage collection in python?
I understand that x becomes an alias for wrapper, but I don't see why the line:
print(x())
should run, especially since I'm not passing in in an string a second time.
I share this because in previous experience I usually have to pass in arguments to make a function that requires arguments execute. To me it seems like the string arg is just hanging around and I'm able to use it in later line even though, I didn't pass anything in the second time.
print((x())
seems like a loophole in python's garbage collection, if I understand correctly.