""" Some hacks. Written by Thomas Karolski (Thomas.Karolski@googlemail.com). Last edit: 11.11.07 """ def getframe(level=0): try: raise Exception() # make an error happen except: # and return the caller's frame import sys frame = sys.exc_traceback.tb_frame.f_back i = level while i < 0: if not hasattr(frame,'f_back') or frame.f_back == None: raise Exception("Can't get back "+str(level)+" levels") frame = frame.f_back i += 1 return frame import types import weakref from functools import wraps class WeaklyReferencableMethod: def __init__(self, method): self._im_self = weakref.ref(method.im_self) self._im_class = method.im_class self._im_func = method.im_func #update_wrapper(self._im_func, method) im_self = property(fget=lambda s: s._im_self()) im_class = property(fget=lambda s: s._im_class) im_func = property(fget=lambda s: s._im_func) def __call__(self, *args, **dargs): return self.im_func(self.im_self, *args, **dargs) import types def weakrefhack( what ): """weakrefhack( method ) Checks whether method exists as an attribute inside method.im_self. If it does, a wrapper function is created which calls a WeaklyReferencableMethod class. The class only stores a weak reference to the original methods object instance (im_self). Thus we get 'real' weakly referencable methods. class A: def method( self ): pass a = A() referencable = weakrefhack(a.method) # referencable is a.method now ref = weakref.ref(a.method)""" what_type = type(what) if what_type==types.MethodType: for attrname in dir(what.im_self): if getattr(what.im_self, attrname)==what: wrm = WeaklyReferencableMethod(what) @wraps(what) def wrapper(*args, **dargs): wrm(*args, **dargs) wrapper.im_self = wrm.im_self wrapper.im_func = wrm.im_func wrapper.im_class = wrm.im_class setattr(what.im_self, attrname, wrapper) return wrapper #import weakref #class a: # def m(): # pass # #mya = a() #weakrefhack(mya.m) #ref = weakref.ref(mya.m) #print ref #ref = weakref.ref(mya.m) #print ref