PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Hard
Question 12
Python allows you to apply multiple decorators to a callable object (function, method or class). When your function is decorated with multiple decorators:
- @outer
- @inner
- def function():
- pass
Select the correct statement.
-
A
The
outerdecorator is called to call theinnerdecorator, then theinnerdecorator calls your function. When your function ends it execution, theinnerdecorator takes over control, and after it finishes its execution, theouterdecorator is able to finish its job. -
B
The
outerdecorator is called to call theinnerdecorator, then theinnerdecorator calls your function. When your function ends it execution, theouterdecorator takes over control, and after it finishes its execution, theinnerdecorator is able to finish its job. -
C
The
innerdecorator is called to call theouterdecorator, then theouterdecorator calls your function. When your function ends it execution, theouterdecorator takes over control, and after it finishes its execution, theinnerdecorator is able to finish its job. -
D
The
innerdecorator is called to call theouterdecorator, then theouterdecorator calls your function. When your function ends it execution, theinnerdecorator takes over control, and after it finishes its execution, theouterdecorator is able to finish its job.
Reveal correct answer
Correct answer: A
A.
This correctly describes the order in which decorators are applied and executed. When applying multiple decorators to a function, the decorators are applied from the bottom up. This means:
@inneris applied first, wrapping the function.Then,
@outeris applied, wrapping the result of@inner.
So the sequence works as follows:
The inner decorator (
@inner) wraps the function first.The outer decorator (
@outer) then wraps the result of the inner decorator.When the decorated function is called:
The outer decorator takes control first and calls the inner decorator.
The inner decorator then calls the original function.
After the function finishes execution, control is returned to the inner decorator to complete its execution.
Finally, control is returned to the outer decorator to finish its job.
B.
The order of decorator execution described here is incorrect. The outer decorator finishes after the inner decorator, not before.
C.
This option incorrectly describes the order of decorator application. The decorators are applied from the bottom up, so the inner decorator wraps the function first, followed by the outer decorator.
D.
This option also incorrectly describes the order of decorator application and execution. The inner decorator is wrapped first, not after the outer decorator.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
