First page Back Continue Last page Overview Graphics

Decorators with Parameters

def evening_greeting(func):

def function_wrapper(x):

print("Good evening, " + func.__name__ + " returns:")

func(x)

return function_wrapper

def morning_greeting(func):

def function_wrapper(x):

print("Good morning, " + func.__name__ + " returns:")

func(x)

return function_wrapper

@evening_greeting

def foo(x):

print(42)

foo("Hi")

These two decorators are nearly the same, except for the greeting. We want to add a parameter to the decorator to be capable of customizing the greeting, when we do the decoration.