Question 15: Exploring Decorators for Function Modification

Hello Pythonistas, welcome back.

This question will help you solidify your understanding of how decorators help modify functions without actually changing the code.

Sounds Weird, Right??

Question: Decorators for Function

Given the following decorator function log_execution which prints a message before and after a function’s execution, and the function greet, which simply prints a greeting:

def log_execution(func):
    def wrapper(*args, **kwargs):
        print(f"Executing {func.__name__}...")
        result = func(*args, **kwargs)
        print(f"Finished executing {func.__name__}.")
        return result
    return wrapper

def greet(name):
    print(f"Hello, {name}!")

Option A:

greet = log_execution(greet)

Option B:

@log_execution
def greet(name):
   print(f"Hello, {name}!")













Option B is the correct answer.

  • Explanation: Just take a look at the output of the first option.

Option A: Output

decorators quiz incorrect output

Leave a Reply