This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Decorators, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does a decorator receive and return?
Answer: A function and a replacement callable
Why: A decorator takes a function and returns a callable that usually wraps it.
What does the program output?
def deco(f):
def wrapper():
return f() + "!"
return wrapper
@deco
def hi():
return "hi"
print(hi())Answer: hi!
Why: The wrapper adds an exclamation mark to the original result.
What is @deco above def f equivalent to?
Answer: f = deco(f)
Why: The decorator is applied at definition time and its result replaces the name f.
Why use functools.wraps?
Answer: To preserve the original function metadata
Why: wraps copies the name, docstring, and other metadata to the wrapper.
Complete the module that provides wraps.
from ____ import wrapsAnswer: functools
Why: wraps lives in the functools module.
Complete the decorator return value.
def deco(f):
def wrapper():
return f()
return ____Answer: wrapper
Why: The decorator must return the inner wrapper function.
Complete the parameter that collects positional arguments.
def deco(f):
def wrapper(*args, **kwargs):
return f(*____, **kwargs)
return wrapperAnswer: args
Why: The wrapper forwards all positional arguments through args.
Complete the metadata helper.
from functools import ____Answer: wraps
Why: wraps keeps the decorated function's identity.
What appears on the screen?
def deco(f):
def wrapper():
return f() * 2
return wrapper
@deco
def word():
return "ab"
print(word())Answer: abab
Why: The wrapper doubles the string, so ab becomes abab.
What is printed?
def deco(f):
def wrapper():
return f().upper()
return wrapper
@deco
def word():
return "hi"
print(word())Answer: HI
Why: The wrapper uppercases the result, so hi becomes HI.
What is the output?
def deco(f):
def wrapper():
return "[" + f() + "]"
return wrapper
@deco
def word():
return "ok"
print(word())Answer: [ok]
Why: The wrapper adds square brackets around ok.
What does this code print?
from functools import wraps
def deco(f):
@wraps(f)
def wrapper():
return f()
return wrapper
@deco
def hello():
return "hi"
print(hello.__name__)Answer: hello
Why: wraps copies the original name, so the output is hello.
Try the questions first
Open the practice page for Python Decorators and answer the same 12 questions with instant feedback.