AI engineering glossary · Python advanced

What is decorator?

Decorator: A function that takes another function (or class) and returns a modified version, applied with @name above the definition. Decorators add behaviour such as logging, caching or access checks without editing the original code.

Level: intermediateTopic: Python advanced

Decorator: an example

@timed above def train(): wraps train so every call also reports how many seconds it took.

Decorator in Python

A short example you can run (Python 3.11). The output below is what it really prints.

import functools

def logged(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        print(f"calling {fn.__name__}{args}")
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} returned {result}")
        return result
    return wrapper

@logged
def with_gst(price, rate=0.18):
    return round(price * (1 + rate), 2)

with_gst(999)
print(with_gst.__name__)   # functools.wraps keeps the original name

Output

calling with_gst(999,)
with_gst returned 1178.82
with_gst

Related terms

More Python advanced terms

Where you learn it

Decorator is part of the AI Engineering Program, which teaches it with notes, a hands-on lab and an exam. The first lesson is free.

Before you go

Take the cheat sheet with you

One free PDF: the key AI-engineering terms, formulas and Python idioms. No spam; unsubscribe any time.