Created
February 2, 2017 12:47
-
-
Save bofm/57b2d6ffda2327cecc5822605f8b6ddb to your computer and use it in GitHub Desktop.
Side Effect Python decorator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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