Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object deletes reference to self

Does Python interpreter gracefully handles cases where an object instance deletes the last reference to itself?

Consider the following (admittedly useless) module:

all_instances = []

class A(object):
    def __init__(self):
        global all_instances
        all_instances.append(self)

    def delete_me(self):
        global all_instances
        self.context = "I'm still here"
        all_instances.remove(self)
        print self.context

and now the usage:

import the_module
a = the_module.A()
the_deletion_func = a.delete_me
del a
the_deletion_func()

This would still print I'm still here, but is there a race condition with Python's garbage collector which is about to collect the object instance?
Does the reference to the object's function save the day?
Does the interpreter keep references to the object whose code it is currently executing until it finishes?

like image 611
Jonathan Livni Avatar asked Nov 25 '12 14:11

Jonathan Livni


1 Answers

No, there isn't any such race condition. You are clearing the reference, so the ref count drops to 1 and the object will be cleaned up once you delete the method reference.

The the_deletion_func reference points to a method, which points to the instance (as well as the class), so there is still a reference there.

Currently executing methods have a local variable self, which is a reference to the instance as well, but mostly it's the method wrapper that provides that reference.

like image 101
Martijn Pieters Avatar answered Sep 25 '22 20:09

Martijn Pieters