Skip to content

Instantly share code, notes, and snippets.

@bofm
Created February 2, 2017 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bofm/57b2d6ffda2327cecc5822605f8b6ddb to your computer and use it in GitHub Desktop.
Save bofm/57b2d6ffda2327cecc5822605f8b6ddb to your computer and use it in GitHub Desktop.
Side Effect Python decorator.
from functools import wraps
def side_effect(callback, before=True, after=False):
"""A decorator.
Wraps the decorated function. The callback will be called before and after each
call of the decorated function according to the parameters.
Args:
callback: a function with signature: a_callback(fn, args, kwargs, result=None)
before: bool
after: bool
"""
def decorator(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
before and callback(fn, args, kwargs)
res = fn(*args, **kwargs)
after and callback(fn, args, kwargs, result=res)
return res
return wrapped
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment