Last active
September 23, 2017 04:42
-
-
Save allenyang79/5f047ed8eeaa1adb3939c5ca6bca76d9 to your computer and use it in GitHub Desktop.
practice decorate by wrapt
This file contains hidden or 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
import wrapt | |
import inspect | |
@wrapt.decorator | |
def pass_through(wrapped, instance, args, kwargs): | |
print "call pass_through", wrapped, instance | |
return wrapped(*args, **kwargs) | |
def with_arguments(myarg1, myarg2): | |
@wrapt.decorator | |
def wrapper(wrapped, instance, args, kwargs): | |
print "call with_arguments", myarg1, myarg2 | |
return wrapped(*args, **kwargs) | |
return wrapper | |
@wrapt.decorator | |
def universal(wrapped, instance, args, kwargs): | |
print "call universal", wrapped, instance, args, kwargs | |
if instance is None: | |
if inspect.isclass(wrapped): | |
# Decorator was applied to a class. | |
return wrapped(*args, **kwargs) | |
else: | |
# Decorator was applied to a function or staticmethod. | |
return wrapped(*args, **kwargs) | |
else: | |
if inspect.isclass(instance): | |
# Decorator was applied to a classmethod. | |
return wrapped(*args, **kwargs) | |
else: | |
# Decorator was applied to an instancemethod. | |
return wrapped(*args, **kwargs) | |
@pass_through | |
def foo(a, b): | |
print 'foo called with %s, %s' % (a, b) | |
@with_arguments('x', 'y') | |
def bar(a, b): | |
print 'bar called with %s, %s' % (a, b) | |
@universal | |
def hello(a, b): | |
print 'hello called with %s, %s' %(a, b) | |
class Person(object): | |
@universal | |
def hi(self, a, b): | |
print 'person say hi, %s, %s' % (a, b) | |
if __name__ == '__main__': | |
print "=============================" | |
foo('aa', 'bb') | |
print "=============================" | |
bar('aaa', 'bbb') | |
print "=============================" | |
hello('aaaa', 'bbbb') | |
print "=============================" | |
p = Person() | |
p.hi('a', 'b') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment