Re: [Python-Dev] Class destructor

"Phillip J. Eby" <pje@telecommunity.com> wrote:
But I need to clean up workspace when a class (not object) is deallocated. I can't easily use attributes, as people suggested, because there is no anonymous storage built-in type. I could subvert one of the existing storage types (buffer, string etc.), but that is unclean. And I could write one, but that is excessive.
So far, I have been unable to track down how to get something called when a class is destroyed. The obvious attempts all didn't work, in a variety of ways. Surely there must be a method? This could be in either Python or C.
Have you tried a PyCObject? This is pretty much what they're for:
Oh, yes, I use them in several places, but they don't really help. Their first problem is that they take a 'void *' and not a request for space, so I have to allocate and deallocate the space manually. Now, I could add a destructor to each of them and do that, but it isn't really much prettier than subverting one of the semi-generic storage types for an improper purpose! It would be a heck of a lot cleaner to deallocate all of my space in exactly the converse way that I allocate and initialise it. It would also all me to collect and log statistics, should I so choose. This could be VERY useful for tuning! I haven't done that, yet, but might well do so. All in all, what I need is some way to get a callback when a class object is destroyed. Well, actually, any time from its last use for object work and the time that its space is reclaimed - I don't need any more precise time than that. I suppose that I could add a C object as an attribute that points to a block of memory that contains copies of all my workspace pointers, and use the object deallocator to clean up. If all else fails, I will try that, but it seems a hell of a long way round for what I would have thought was a basic requirement. Regards, Nick Maclaren, University of Cambridge Computing Service, New Museums Site, Pembroke Street, Cambridge CB2 3QH, England. Email: nmm1@cam.ac.uk Tel.: +44 1223 334761 Fax: +44 1223 334679

At 05:24 PM 2/28/2007 +0000, Nick Maclaren wrote:
I suppose that I could add a C object as an attribute that points to a block of memory that contains copies of all my workspace pointers, and use the object deallocator to clean up. If all else fails, I will try that, but it seems a hell of a long way round for what I would have thought was a basic requirement.
Well, you could use a custom metaclass with a tp_dealloc or whatever. But I just mainly meant that a PyCObject is almost as good as a weakref for certain purposes -- i.e. it's got a pointer and a callback. You could of course also use weak references, but that's a bit more awkward as well.
participants (2)
-
Nick Maclaren
-
Phillip J. Eby