Lesson 55 of 60
โฎPrev Nextโฏ

PY-101 ยท Advanced Python

Decorators

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

55of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    A decorator is a function that takes another function and returns a new function that adds something before or after it, such as logging or a permission check. Writing @my_decorator above def is shorthand for func = my_decorator(func). Frameworks use decorators everywhere, for example @app.get("/") in FastAPI.

    • Pass functions around like values
    • Write a wrapper decorator
    • Read @decorator syntax

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Decorators, running
    1. from functools import wraps
    2. def log_calls(func):
    3. @wraps(func)
    4. def wrapper(*args, **kwargs):
    5. print("Calling", func.__name__, args)
    6. result = func(*args, **kwargs)
    7. print("Returned", result)
    8. return result
    9. return wrapper
    10. @log_calls
    11. def add(a, b):
    12. return a + b
    13. add(2, 3)
    14. print(add.__name__)
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemYou want to log every time 20 different functions are called. Adding print lines to all 20 is messy. One decorator, written once and placed above each, does it.
    2. The Python ideadef deco(func):A decorator is a function that takes another function and returns a new function that adds something before or after it, such as logging or a permission check.
    3. In real lifeFastAPI routes are decorators: @app.get("/users") registers the function underneath as the handler for that URL.

    Start with a question

    You want to log every time 20 different functions are called. Adding print lines to all 20 is messy. One decorator, written once and placed above each, does it.

    Web routes, caching, retries, timing and access checks are all decorators in real projects.

    Explain it like I'm 10

    A decorator is gift wrapping: the present (the function) is unchanged, but now there is a bow and a card around it.

    The technical explanation

    Functions are values: you can pass them to other functions and return them.

    A decorator defines an inner wrapper(*args, **kwargs) that does extra work and calls the original.

    @shout above def greet replaces greet with shout(greet).

    Syntax

    def deco(func):
        def wrapper(*args, **kwargs):
            ...
            return func(*args, **kwargs)
        return wrapper
    
    @deco
    def f(): ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    FastAPI routes are decorators: @app.get("/users") registers the function underneath as the handler for that URL.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. @deco above def f is the same as?
    2. 2. What does a decorator usually return?
    3. 3. Why use *args, **kwargs in the wrapper?
    4. 4. What does functools.wraps keep?
    5. 5. Common real use of decorators?

    Questions people ask

    Are decorators only for functions?

    They can wrap classes too (for example @dataclass). The idea is the same: take something, return an enhanced version.

    Can I stack decorators?

    Yes. Several @ lines stack; the one closest to def is applied first.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Are decorators only for functions?

    They can wrap classes too (for example @dataclass). The idea is the same: take something, return an enhanced version.

    beginner Can I stack decorators?

    Yes. Several @ lines stack; the one closest to def is applied first.

    intermediate @deco above def f is the same as?

    f = deco(f). The function is passed to the decorator.

    intermediate What does a decorator usually return?

    A new wrapper function. It returns the wrapper.

    Quick revision

    Remember

    • Pass functions around like values
    • Write a wrapper decorator
    • Read @decorator syntax
    • Use functools.wraps(func) on your wrapper so the decorated function keeps its real name and docstring.

    Syntax

    def deco(func):
        def wrapper(*args, **kwargs):
            ...
            return func(*args, **kwargs)
        return wrapper
    
    @deco
    def f(): ...

    Official documentation