What's the difference in Python between deleting an object and letting it go out of scope?

Viewed 248

I'm working on a multithreaded Python extension in C that deals a fair bit with the GIL.

There's a problem at exit where code like this shuts down cleanly:

from myextension import ExtensionObject

obj = ExtensionObject()
obj.start()
time.sleep(5)
del obj
# Interpreter exits here

But, if I remove the del obj from the end and let obj go out of scope and get deleted automatically, I get a deadlock while trying to acquire the GIL to do some cleanup in one of the spawned threads.

Is there a fundamental difference between deleting an object and just letting it go out of scope, specifically when it's at the end of program execution?

Edit: Note also that obj = None does the same thing as del obj in this scenario.

1 Answers

There is no fundamental difference because it is always the garbage collection which does the deleting.

  1. You can never delete an object. del obj actually deletes the variable and not the object it refers to.
  2. Going out of scope is the only way for an object to get deleted.

Both of the above can be defeated by having the variable be referred to by something else:

obj = ExtensionObject()
other = obj  # now there are two labels for your instance.
del obj   # now we have lost obj, but 'other' keeps the instance alive.
Related