[Python-Dev] Object creation hook

Mike Klaas mike.klaas at gmail.com
Tue Jan 23 21:51:38 CET 2007


On 1/23/07, Kristján V. Jónsson <kristjan at ccpgames.com> wrote:

> Hello there.
>
> I am trying to insert a hook into python enabling a callback for all
> just-created objects.  The intention is to debug and find memory leaks, e.g.
> by having the hook function insert the object into a WeakKeyDictionary.
>
> I have already added a method to "object" to set such a hook, and
> "object_new" now calls it upon completion, but this is far from covering all
> places.  Initially, I thought object_init were the place, but almost no
> classes call object.__init__ from their __init__ method.  Then there is the
> separate case of old-style classes.
>
>
>
> Any suggestions on how to do a global object creation hook in python?

When I've used such things in the past, I usually had some idea which
classes I was interested in targeting.  I used a metaclass for doing
the tracking, and either invoked it on individual classes, or used
__metaclass__ = X to apply it (something like "class object(object):
__metaclass__ = X" would do the try for new-style class that inherit
from object directly).

-Mike


More information about the Python-Dev mailing list