1. LPU MCA Semester 1
  2. CAB106
  3. Unit 4

CAB106 · Unit 4: Abstraction, modules and packages

Decorators introduction

11 practice questions

Key points

  • @deco is f = deco(f), applied at definition time
  • Stacked decorators apply from the bottom up
  • functools.wraps keeps __name__ and __doc__
  • A decorator must return a callable

A decorator is a function that takes a function and returns a new function, usually a wrapper that adds behaviour before or after the original. The syntax @deco above a definition is shorthand for f = deco(f), so it rebinds the function's name to the wrapper.

IdeaDetail
TimingA decorator runs once, when the function is defined
StackingApplied bottom-up: @a above @b means a(b(f))
Arguments@repeat(3) calls repeat(3) first, which returns the real decorator
Metadatafunctools.wraps(f) keeps the original __name__ and __doc__
Return valueA decorator must return a callable; returning None breaks the function

Wrappers usually accept *args and **kwargs so they work with any signature, and pass the result back. Functions are objects, so a wrapper may store state on itself, such as a call counter attribute.

Exam trap: without functools.wraps the decorated function reports the wrapper's name, not its own, and a decorator that forgets to return the wrapper replaces the function with None.

Try two questions

Question 1 · Tier 1, Recall

A decorator is best described as

  1. a comment that explains what a function is meant to do
  2. a class that is not allowed to contain any methods
  3. a function that takes a function and returns a new function wrapping it
  4. a keyword that deletes a function after its first use
Show the answer

C. A decorator adds behaviour around a function without editing its code.

Why not A: A comment is ignored by Python and does not change behaviour.

Why not B: Decorators are usually functions, and classes may have methods.

Why not D: Python has no such keyword.

Question 2 · Tier 1, Recall

Which symbol is used to apply a decorator above a function definition?

  1. #
  2. @
  3. &
  4. %
Show the answer

B. Writing @name above a def applies the decorator name to that function.

Why not A: # starts a comment.

Why not C: & is the bitwise AND operator.

Why not D: % is the remainder operator.