Created
April 29, 2013 06:45
-
-
Save sidchilling/5480078 to your computer and use it in GitHub Desktop.
Script to show how to use a decorator maker to pass arguments to a 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
# To show how we can pass arguments to decorators. We will use the decorator maker pattern | |
# that we saw in the previous example | |
def decorator_maker_with_args(decorator_arg1, decorator_arg2): | |
print 'I make decorators. And I accept arguments: %s, %s' %(decorator_arg1, | |
decorator_arg2) | |
def my_decorator(func): | |
# This is the decorator. The ability to pass arguments here is because of closure | |
print 'I am the decorator. You passed me arguments: %s, %s' %(decorator_arg1, | |
decorator_arg2) | |
# Do not confuse between decorator arguments with function arguments | |
def wrapper(function_arg1, function_arg2): | |
print 'I am the wrapper function. Decorator arguments: (%s, %s). Function arguments: (%s, %s)' \ | |
%(decorator_arg1, decorator_arg2, function_arg1, function_arg2) | |
return func(function_arg1, function_arg2) | |
return wrapper | |
return my_decorator | |
arg1 = 'Ron Weasley' | |
@decorator_maker_with_args(arg1, 'Harry Potter') | |
def decorated_function_with_arguments(func_arg1, func_arg2): | |
print 'I am the decorated function. Args: %s, %s' %(func_arg1, func_arg2) | |
print '\n\n\n' | |
decorated_function_with_arguments('Hermione Granger', 'Ginny Weasley') | |
print '\n\n\n' | |
decorated_function_with_arguments('Hermione Granger', 'Ginny Weasley') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment