Reputation: 165
I've read over this great post: How to make a chain of function decorators?
I decided to fiddle around with it and I'm taking this block from it:
# It’s not black magic, you just have to let the wrapper
# pass the argument:
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(arg1, arg2):
print "I got args! Look:", arg1, arg2
function_to_decorate(arg1, arg2)
return a_wrapper_accepting_arguments
# Since when you are calling the function returned by the decorator, you are
# calling the wrapper, passing arguments to the wrapper will let it pass them to
# the decorated function
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print "My name is", first_name, last_name
print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman
What if, instead of just renaming the decorated print_full_name(first_name, last_name)
as itself, I wanted to save the decorated version as a different function name, like decorated_print_full_name(first_name, last_name)
? Basically, I'm more curious as to how I change the code so I DON'T use the @a_decorator_passing_arguments
shortcut.
I rewrote the above (for Python 3):
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(arg1, arg2):
print("I got args! Look:", arg1, arg2)
function_to_decorate(arg1, arg2)
return a_wrapper_accepting_arguments
#@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print("My name is", first_name, last_name)
decorated_print_full_name = a_decorator_passing_arguments(print_full_name(first_name, last_name))
decorated_print_full_name("Peter", "Venkman")
but Python complains that first_name
is not defined in line 11. I'm still new to Python so forgive me if I missed something very obvious here.
Upvotes: 0
Views: 89
Reputation: 74645
It should work with:
decorated_print_full_name = a_decorator_passing_arguments(print_full_name)
Upvotes: 1