Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Stack Multiple Decorators on One Function

Learn to combine multiple decorators into a single decorator factory so you can apply several wrappers at once in a predictable order.

Python practice15 minDecorators FundamentalsIntermediateLast updated April 15, 2026

Problem statement

In Python you can stack multiple decorators using multiple @ lines above a function. For readability and reuse you may want a single decorator factory that composes several decorators into one. Implement compose_decorators(*decorators) which returns a decorator that, when applied to a function, applies the provided decorators in the same top-to-bottom order as multiple @ lines. For example, compose_decorators(d1, d2)(f) should produce the same result as applying @d1 and then @d2 above f (i.e. f = d1(d2(f))). The function should accept zero or more decorators. If no decorators are given, compose_decorators() should behave like the identity decorator (return the function unchanged). Use the provided helper decorators in tests to validate behavior.

Task

Implement a compose_decorators utility that stacks any number of decorators and applies them in the same order as writing multiple @decorator lines.

Examples

Compose prefix and uppercase decorators

Input

greet('alice')

Output

Hi ALICE

compose_decorators(add_prefix('Hi '), uppercase) applies uppercase first, then add_prefix, producing 'Hi ALICE'.

Input format

This exercise defines and uses functions and decorators. Tests will call decorated functions with regular Python arguments (strings and numbers).

Output format

Each test evaluates an expression and compares the returned value's string representation to the expected string.

Constraints

Do not modify the provided helper decorators or the decorated functions used in tests. Implement compose_decorators to correctly handle any number of decorators, including zero.

Samples

Sample 1

Input

compute(4)

Output

18

compose_decorators(multiply(3), add(2)) makes compute return (x + 2) * 3, so compute(4) -> (4+2)*3 = 18.