Python, from Zero, for AILesson 66 of 89

Module 7 · Objects, generators and the shape a larger program takes

Decorators: wrapping a function with retry, timing or a cache

In this lesson

  • 9 min read
  • 8 reading sections
  • Knowledge check
  • Lesson 7 of 10 in this chapter

This chapter’s goalRestructure a growing script into classes and dataclasses with a swappable provider behind one interface, implement the dunder methods that let your objects work with for, len, in and with, write a decorator that retries or caches, run a type checker and act on its output, make the project installable as a command with pyproject.toml, and profile it to say from measurement rather than guesswork where the time goes.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:40Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 10Free · no account needed
Lesson steps

Functions are values

You met this in module 3 when you passed a function to sorted as key=. A function can be stored in a variable, put in a list, passed as an argument, and returned from another function. A decorator uses all of that at once.

Python
def shout(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result.upper()
    return wrapper

def greet(name):
    return f"hello {name}"

greet = shout(greet)
print(greet("asha"))          # HELLO ASHA

shout receives greet, builds a new function wrapper that calls greet and changes the result, and returns wrapper. The last line replaces the name greet with the wrapper. The @ syntax is that last line moved to the top:

Python
@shout
def greet(name):
    return f"hello {name}"

Identical meaning. @shout above a def means “after defining this, pass it through shout and bind the result to the same name”. That is all the syntax does.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Decorators: wrapping a function with retry, timing or a cache’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/decorators (Accessed: 21 November 2026).