Tracking object allocation in python -
is there method can override allow me use print statements / pdb / etc. keep track of every time instance of class allocated? while unpickling objects seeming never have either __setstate__
or __init__
called on them. tried overriding __new__
, printing out id of every object make in __new__
, still encountering objects ids never printed.
edit: here code use altering (instrumenting) __new__
of class , of super-classes except object
itself:
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)+' id '+str(id(rval)) return rval def replace_allocator(cls): if cls == object: return setattr(cls,'__new__',allocator(cls).new) print cls.__base__ try: parent in cls.__base__: replace_allocator(parent) except: replace_allocator(cls.__base__)
i call replace_allocator on classes' parent class imported in main script. class has custom __new__
begin with, prints out id.
(this more of comment answer.)
quoting guido's unifying types , classes in python 2.2:
there situations new instance created without calling
__init__
(for example when instance loaded pickle). there no way create new instance without calling__new__
(although in cases can away calling base class's__new__
).
if using new-style classes (descendants of object
), __new__()
should called. don't think obscure cases "you can away calling base class's __new__
" in happen accidently, though don't know these cases are.
and add example:
in [1]: class a(object): ...: def __new__(cls): ...: print "a" ...: return object.__new__(cls) ...: in [2]: a() out[2]: <__main__.a object @ 0xa3a95cc> in [4]: object.__new__(a) out[4]: <__main__.a object @ 0xa3a974c>
Comments
Post a Comment