Deleting objects
Shalabh Chaturvedi
shalabh at cafepy.com
Thu Jan 15 01:31:09 EST 2004
user at domain.invalid wrote:
> Say I have an object (foo), that contains an
> array (bar) of references to other objects.
>
> Now I want to puff some of the objects from the
> array so that I remove the array element, and
> destroy the oject.
You don't need to jump through hoops for this. All you need to do is:
del foo
If there are no other references to the object that was called foo
above, then (and only then) it will be destroyed.
Python keeps a reference count for each object. When the count hits 0
(no references pointing to object) it is destroyed.
Because of this, attributes of foo (eg foo.bar) will automatically be
destroyed when foo is destroyed (assuming they don't have references
from elsewhere).
>
> but when I do:
>
> del foo.bar[0]
>
> Python says:
> object doesn't support item deletion
>
> So do I need to define __del__? And what would I
> put there?
What is the type of foo.bar?
>
> What if I wanted to remove the array element
> but still have the object exist?
del foo.bar
This will remove the reference foo.bar.
> What happens if I succeed in destroying an object
> that other objects still think they are referencing?
Try as you might, shooting yourself in the foot is pretty hard in Python
(see above :)
--
Shalabh
More information about the Python-list
mailing list