Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.7 — Decorators with Arguments and Class Decorators
Python · Example 1 of 2

Decorators with arguments

Change times=3 to times=2, and attempts=4 to attempts=2 to see the retry give up.

A decorator that takes its own settings, such as @retry(attempts=3), needs three levels of functions: one to take the settings, one to take the function, one to wrap the call. Decorators can also be written as classes, applied to methods, and applied to whole classes.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a decorator factory prefix(text) that adds text in front of the string a function returns. Use @prefix(">> ") on a function returning "hi" and print the result.

02

Write a class decorator add_hello that adds a method hello to a class, returning "hello from " + the class name. Apply it to class Dog and call Dog().hello().

03

Write a decorator factory limit_calls(n) that lets a function run only n times and raises RuntimeError("limit reached") on the next call. Show it with n=2.

Explain it without notes

01

How does a decorator that takes arguments work? Describe the three levels.

02

How would you write a decorator that works both with and without brackets?

03

What is the difference between a class decorator and a decorator written as a class?

04

Why can a class-based decorator be awkward on methods?

05

In what order are the arguments of stacked decorator factories evaluated, and when does each part of a three-level decorator run?

Decorators with arguments
Sign in to run this example in your browser.

Expected output

hello Ada
hello Ada
hello Ada
attempt 1/4 failed: timeout
attempt 2/4 failed: timeout
ok