- LPU MCA Semester 1
- CAB106
- 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.
| Idea | Detail |
|---|---|
| Timing | A decorator runs once, when the function is defined |
| Stacking | Applied bottom-up: @a above @b means a(b(f)) |
| Arguments | @repeat(3) calls repeat(3) first, which returns the real decorator |
| Metadata | functools.wraps(f) keeps the original __name__ and __doc__ |
| Return value | A 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
A decorator is best described as
- a comment that explains what a function is meant to do
- a class that is not allowed to contain any methods
- a function that takes a function and returns a new function wrapping it
- 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.
Which symbol is used to apply a decorator above a function definition?
- #
- @
- &
- %
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.