Reputation: 3559
I am building a Python wrapper for a swig interface for a C++ program.
I am interested in knowing if there is a way for a Python object to "know" how it was deleted. The idea is simple, if the object was deleted by the garbage collector the wrapper would do nothing to the underlying C++ object, but if the user deleted the object on purpose (``del object) then the wrapper would detect that and un-reference the underlying object so that it also get deleted.
I tried googling about this already, but could not find anything. The only thing I found is that (apparently) __del__
is called by both the garbage collector and the del command, and it seems that there is no way to distinguish which one called it.
Hoping someone proves me wrong!
Upvotes: 2
Views: 659
Reputation: 1122552
CPython uses reference counting to track object lifetimes. Thus, all deletions are done by the garbage collector.
For example, the following code creates two references; the __del__
hook only is called once, after the second reference to the object is deleted:
>>> class Foo(object):
... def __del__(self):
... print "Bye bye!"
...
>>> spam = Foo()
>>> bar = spam
>>> del spam
>>> del bar
Bye bye!
Thus, there is no way to detect an individual del
statement through the __del__
hook; it is always only called by the garbage collector.
Note that certain python implementations (most notably cpython), do not clear objects with a __del__
hook that are part of a circular dependency. This does not apply to all implementations, but it bears remembering.
In any case, the use of reference counting to implement object deletion and garbage collection is itself an implementation detail, and non-CPython implementations could (and do) handle object deletion differently altogether.
Upvotes: 2