Jonathan Stein Jonathan Stein - 8 months ago 49
Python Question

Are objects erased from memory when a function finishes? Python

Say there is

class thing(object):
def __init__(self):
self.text = "foo"

def bar():
obj = thing()
#do something with the object


Is obj deleted from memory after bar() finishes, or is it still in memory, just can't be accessed since it is a local variable of bar? (This assumes obj is not put into a global or external container such as a dictionary or list, of course).


The object obj references will be deleted when the function exits.

That's because CPython (the default Python implementation) uses reference counting to track object lifetimes. obj is a local variable and only exists for the duration of the function. thing() is an instance with just one reference, obj, and when obj is cleaned up, the reference count drops to 0 and thing() is immediately deleted.

If you are using PyPy, IronPython, Jython or some other implementation, object destruction can be delayed as implementations are free to use different garbage collection schemes. This is only important for implementing a __del__ method, as their invocation can be delayed.

I recommend you read the excellent Facts and myths about Python names and values if you want to know more about how Python names work.