Get startedGet started for free

Defining a decorator

Your buddy has been working on a decorator that prints a "before" message before the decorated function is called and prints an "after" message after the decorated function is called. They are having trouble remembering how wrapping the decorated function is supposed to work. Help them out by finishing their print_before_and_after() decorator.

This exercise is part of the course

Writing Functions in Python

View Course

Exercise instructions

  • Call the function being decorated and pass it the positional arguments *args.
  • Return the new decorated function.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

def print_before_and_after(func):
  def wrapper(*args):
    print('Before {}'.format(func.__name__))
    # Call the function being decorated with *args
    ____(*args)
    print('After {}'.format(func.__name__))
  # Return the nested function
  return ____

@print_before_and_after
def multiply(a, b):
  print(a * b)

multiply(5, 10)
Edit and Run Code