Created
November 27, 2013 01:06
-
-
Save leepro/7669110 to your computer and use it in GitHub Desktop.
Make a proxy for all methods of a class using metaclass.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
class TraceMeta(type): | |
def __new__(meta, name, bases, dct): | |
for name,func in dct.items(): | |
print "\"%s\"" % name, "-->", "\"%s\"" % func | |
if name[0]!="_" and len(repr(func))>10: | |
if repr(func)[:5] == "<func": | |
dct["_"+name] = dct[name] | |
dct[name].func_name = "_"+dct[name].func_name | |
def makeproxy(n, fc): | |
f_name = n | |
f_func = fc | |
@wraps(fc) | |
def proxy(self, *args, **kwargs): | |
print ">> before << ", f_func | |
ret = f_func(self, *args, **kwargs) | |
print ">> after <<", ret | |
return ret | |
return proxy | |
dct[name] = makeproxy(name, dct[name]) | |
return super(TraceMeta, meta).__new__(meta, name, bases, dct) | |
def __init__(cls, name, bases, dct): | |
super(TraceMeta, cls).__init__(name, bases, dct) | |
class MyClass(object): | |
"""sdfasdfasdf""" | |
__metaclass__ = TraceMeta | |
value = 0 | |
def __init__(self, value): | |
self.value = value | |
def test(self, msg, hint=None): | |
"""my name is tests""" | |
print msg, self.value, hint | |
self.value+=1 | |
return self.value | |
def hi(self, msg): | |
print msg, self.value | |
self.value+=1 | |
return self.value | |
def bye(self): | |
print "final" | |
return self.value | |
if __name__=="__main__": | |
foo = MyClass(4) | |
print foo.hi("hi") | |
print foo.hi("hio") | |
print foo.test("good", hint=1111) | |
print foo.test.__doc__ | |
print foo.bye() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment