Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

bar()

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).

like image 242
13steinj Avatar asked Dec 27 '15 16:12

13steinj


1 Answers

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.

like image 192
Martijn Pieters Avatar answered Oct 17 '22 02:10

Martijn Pieters