Skip to content

Instantly share code, notes, and snippets.

@martinth
Last active January 21, 2018 01:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinth/5815159 to your computer and use it in GitHub Desktop.
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
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