For example, in the code:
a = [1, 2, 3, 4] # huge list
y = sum(a)
print( do_stuff(y) )
Will the memory for the list a
ever get freed up before the program ends? Will the do_stuff
function call have to do all its stuff with a
constantly taking up memory, even though a
's never going to be used again?
And if a
doesn't get garbage collected, is the solution to manually set a=None
once I'm done using it?
CodePudding user response:
Imagine do_stuff
did this:
def do_stuff(y):
return globals()[input()]
And the user enters a
, so that the list is used there after all. Python can't know that that won't happen, it would have to read the user's mind.
Consider a trivial case like this:
def do_stuff(y):
return y
Now it's clear that a
doesn't get used anymore, so Python could figure that out right? Well... print
isn't a keyword/statement anymore. Python would have to figure out that you didn't overwrite print
with something that does use a
. And even if you didn't, it would need to know that its own print
doesn't use a
.
You'll have to delete it yourself. I'd use del a
. (Unless you want a
to still exist and have the value None
).
CodePudding user response:
a
will never be freed unless it goes out of scope (ie. it was in a function to begin with), or you manually set it to None
.
Python's garbage collector uses a system called reference counting. In short, all variables have a reference counter that is incremented when a reference to the variable is created, and decremented when an variable is set to None
or when it goes out of scope.
Example:
a = [999999] # 1 reference, the value [999999] is stored in memory
b = a # 2 references
def foo(x):
print(x)
foo(a) # 3 references during the function call
# back to 2 references
a = None # 1 reference
b = None # 0 references, the value [999999] is deleted from memory