Skip to content

    Decorators

    Python · Intermediate

    Definition

    A decorator is a function that wraps another function to add behavior without changing its code.

    Used for logging, timing, caching and access checks.

    Diagram

    @logdef f()log(f) → wrapper

    Flowchart

    Define wrapper functionCall original insideReturn wrapperApply with @decorator

    Example: Logging decorator

    def log(fn):
        def wrap(*a):
            print('calling', fn.__name__)
            return fn(*a)
        return wrap
    @log
    def add(x, y): return x + y
    print(add(2, 3))

    Output: calling add 5

    Key points

    • Use functools.wraps to keep the name
    • functools.lru_cache is a built-in decorator

    Interview questions

    What is lru_cache?

    A decorator that memoizes function results by arguments.

    More Python topics