Skip to content

Instantly share code, notes, and snippets.

@carlozamagni
Last active August 29, 2015 13:57
Show Gist options
  • Save carlozamagni/9917234 to your computer and use it in GitHub Desktop.
Save carlozamagni/9917234 to your computer and use it in GitHub Desktop.
A collection of (not really) AOP python decorators.
'''
Intended to be used like this:
'''
@After(my_after_func) # my_after_func gets called with the same arguments passed to 'sut_func'
@Before(my_before_func) # as above
@SendResultTo(my_related_func) # my_related_func gets invoked after 'sut_func': my_related_func(**sut_result)
def sut_func(*args, **kwargs):
return 'blah blah'
class After(object):
def __init__(self, execute_fn):
self.execute_fn = execute_fn
def __call__(self, fn):
def executor(*args, **kwargs):
fn(*args, **kwargs)
try:
self.execute_fn(*args, **kwargs)
except Exception, e:
# log exception, explode, do something...
pass
return executor
class Before(object):
def __init__(self, execute_fn):
self.execute_fn = execute_fn
def __call__(self, fn):
def executor(*args, **kwargs):
try:
self.execute_fn(*args, **kwargs)
except Exception, e:
# log exception, explode, do something...
pass
fn(*args, **kwargs)
return executor
class SendResultTo(object):
def __init__(self, execute_fn):
self.execute_fn = execute_fn
def __call__(self, fn):
def executor(*args, **kwargs):
results = fn(*args, **kwargs)
try:
self.execute_fn(**results)
except Exception, e:
# log exception, explode, do something...
pass
return results
return executor
'''
@Around could be defined as an aggregation of @Before and @After
maybe not so useful
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment