Skip to content

Instantly share code, notes, and snippets.

@dmiro
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save dmiro/3fb64c19ea413591feb9 to your computer and use it in GitHub Desktop.

Select an option

Save dmiro/3fb64c19ea413591feb9 to your computer and use it in GitHub Desktop.
Python @decorator to create decorator
"""
Python @decorator to create decorator
http://librosweb.es/eventos/pycon-2014/como-crear-decorators-avanzados-en-las-aplicaciones-python/
"""
import functools
class object_proxy(object):
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__name__= wrapped.__name__
except AttributeError:
pass
@property
def __class__(self):
return self.wrapped.__class__
def __get_attr__(self, name):
return getattr(self.wrapped, name)
class bound_function_wrapper(object_proxy):
def __init__(self, wrapped, wrapper):
super(bound_function_wrapper, self).__init__(wrapped)
self.wrapper = wrapper
def __call__(self, *args, **kwargs):
return self.wrapper(self.wrapped, args, kwargs)
class function_wrapper(object_proxy):
def __init__(self, wrapped, wrapper):
super(function_wrapper, self).__init__(wrapped)
self.wrapper = wrapper
def __get__(self, instance, owner):
wrapped = self.wrapped.__get__(instance, owner)
return bound_function_wrapped(wrapped, self.wrapper)
def __call__(self, *args, **kwargs):
return self.wrapper(self.wrapped, args, kwargs)
def decorator(wrapper):
@functools.wraps(wrapper)
def _decorator(wrapped):
return function_wrapper(wrapped, wrapper)
return _decorator
#test 1
@decorator
def my_function_wrapper(wrapper, args, kwargs):
print "hello from decorator"
return wrapper(*args, **kwargs)
@my_function_wrapper
def function():
print "hello from function"
return
function()
#result
"""
hello from decorator
hello from function
"""
#test 2
@decorator
def my_function_wrapper(wrapper, args, kwargs):
print "hello %s from decorator" % args[0]
r = wrapper(*args, **kwargs)
print "goodbye %s from decorator you say %s " % (args[0], r)
return r
@my_function_wrapper
def function(name):
print "hello from function"
return "yes!"
function("David")
#result
"""
hello David from decorator
hello from function
goodbye David from decorator you say yes!
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment