Skip to content

Instantly share code, notes, and snippets.

@luiscoms
Created September 12, 2016 14:23
Show Gist options
  • Save luiscoms/8f34e76172431c3a41c6d967877812e0 to your computer and use it in GitHub Desktop.
Save luiscoms/8f34e76172431c3a41c6d967877812e0 to your computer and use it in GitHub Desktop.
Python Wrapper behaviours
from functools import wraps
def dec_wrapper(name):
def dec(func):
@wraps(func)
def wrapper(*args, **kw):
print(name)
print(args)
result = func(*args, **kw)
print('acabou')
return result
return wrapper
if hasattr(name, '__call__'):
return dec(name)
return dec
@dec_wrapper('nome do decorator')
def funca(a,b):
return a+b
@dec_wrapper
def funcb(a,b):
return a+b
class MyDecorator:
def __init__(self, name):
self.name = name
def __call__(self, func):
self.func = func
return self.wrapper
def wrapper(self,a,b):
print('oi')
result = self.func(a,b)
print('tchau')
return result
def mydec(*args, **kwargs):
if args and hasattr(args[0], '__call__'):
return MyDecorator('no name')(args[0])
return MyDecorator(*args, **kwargs)
@mydec('nome')
def func2(a,b):
return a+b
@mydec
def func3(a,b):
return a+b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment