Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Advanced decorator builder / customization
"""
Exploring some ideas around customizable decorators that derive default
values from a config or instance.
"""
from functools import wraps
# Simple customizable decorator.
def deco_factory(prefix=''):
"""Decorator factory that saves some config options.
This is for all decorator calls.
"""
def outer(func):
@wraps(func)
def inner(*args, **kwargs):
print('{0} Woot!'.format(prefix))
return func(*args, **kwargs)
return inner
return outer
adeco = deco_factory(prefix='<>')
@adeco
def myfunc():
print('hello this is my func.')
print('\n')
myfunc()
# More involved class based config.
# The important distinction being it is a class instance that can
# have more configuration, and properties.
class Wrapper(object):
def __init__(self, prefix='', default_msg='Hello!'):
self._prefix = prefix
self._msg = default_msg
@property
def prefix(self):
return self._prefix
def get_helper(self):
def outer(func):
@wraps(func)
def inner(*args, **kwargs):
print('{0} {1}'.format(self._prefix, self._msg))
return func(*args, **kwargs)
return inner
return outer
def get_helper2(self):
"""A more involved, customizeable decorator.
Customized at the class level, and also per-call.
"""
def _f(extra=None):
def outer(func):
@wraps(func)
def inner(*args, **kwargs):
if extra is not None:
print('This is the extra stuff! ')
print(extra)
print('End extra stuff!')
print('{0} {1}'.format(self._prefix, self._msg))
return func(*args, **kwargs)
return inner
return outer
return _f
mywrapper = Wrapper(prefix='><', default_msg='Good day!')
@mywrapper.get_helper()
def myfunc2():
print('hello this is my func.')
print('\n')
wrapper2 = mywrapper.get_helper2()
@wrapper2(extra='Weeee')
def myfunc3():
print('hello this is my func2.')
print('\n')
myfunc2()
myfunc3()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment