Last active
January 21, 2018 01:09
-
-
Save martinth/5815159 to your computer and use it in GitHub Desktop.
A sample decorator the can be used on plain old functions and also on instance methods
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
class func_and_method_decorator(object): | |
'''A clased based decorator that takes parameters and works on plain functions | |
and instance methods''' | |
def __init__(self, *args, **kwargs): | |
'''The init function is called when a module where the decorator is used | |
is imported. It gets passed all parameters that are given to decorator | |
definition. I.e. | |
@func_and_method_decorator(foo='bar') | |
would result in | |
kwargs = {'foo': 'bar'} | |
''' | |
print "func_and_method_decorator init called", args, kwargs | |
def __call__(self, func): | |
import functools | |
print "func_and_method_decorator __call__ called" | |
@functools.wraps(func) | |
def decorated(*args, **kwargs): | |
'''This is the function that wraps the actual function call. It is | |
called when the decorated function or method is called. It can check | |
or modify the parameter and/or result''' | |
print "func_and_method_decorator decorated function called with", args, kwargs | |
result = func(*args, **kwargs) | |
print "func_and_method_decorator decorated function result is", result | |
return result | |
return decorated |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment