Skip to content

Instantly share code, notes, and snippets.

@billyshambrook
Last active August 29, 2015 13:56
Show Gist options
  • Save billyshambrook/8973012 to your computer and use it in GitHub Desktop.
Save billyshambrook/8973012 to your computer and use it in GitHub Desktop.
Passing around arguments in decorators
"""
Create argument within decorator and pass to decorated method.
Key things that make this possible is to ensure that your decorated method allows *args and **kwargs to be passed.
You then within the decorator append whatever to kwargs and/or args.
"""
def decorate_my_decorator(f):
def function_my_decorator(*args, **kwargs):
kwargs['somethings'] = 'hello'
return f(*args, **kwargs)
return function_my_decorator
@decorate_my_decorator
def b_decorated_method(*args, **kwargs):
print kwargs.get('somethings')
b_decorated_method()
################
################
"""
Parse argument into the decorator and access it from the decorated method.
This builds on from the above but the decorator is itself wrapped with another method that allows the argument that you
wish to pass in. This argument is then accessible down the tree of methods.
"""
def my_decorator(somethings='argument'):
def decorate_my_decorator(f):
def function_my_decorator(*args, **kwargs):
kwargs['somethings'] = somethings
return f(somethings, *args, **kwargs)
return function_my_decorator
return decorate_my_decorator
@my_decorator(somethings='my_own_value')
def a_decorated_method(*args, **kwargs):
print kwargs['somethings']
a_decorated_method()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment