title: Tracking object allocation in python
body: <p>Is there any method I can override that will allow me to use print statements / pdb / etc. to keep track of every time an instance of my class is allocated? While unpickling some objects I am seeming to get some that never have either <code>__setstate__</code> or <code>__init__</code> called on them. I tried overriding <code>__new__</code> and printing out the id of every object I make in <code>__new__</code>, but I am still encountering objects with ids that were never printed.</p>
  
  <p>Edit: here is my code I use for altering (instrumenting) <code>__new__</code> of my class and all of its super-classes except for <code>object</code> itself:</p>
  
  <pre><code>class Allocator:
      def __init__(self, my_class):
         self.my_class = my_class
         self.old_new = my_class.__new__
  
      def new(self, * args, ** kargs):
          rval = self.old_new(*args, ** kargs)
          #rval = super(self.my_class,cls).__new__(cls)
          print 'Made '+str(self.my_class)+' with id '+str(id(rval))
          return rval
  
  def replace_allocator(cls):
      if cls == object:
          return
  
      setattr(cls,'__new__',Allocator(cls).new)
      print cls.__base__
  
      try:
          for parent in cls.__base__:
              replace_allocator(parent)
     except:
          replace_allocator(cls.__base__)
  </code></pre>
  
  <p>I call replace_allocator on my classes' parent class as soon as it is imported in the main script. My class has a custom <code>__new__</code> to begin with, which also prints out the id.</p>