MediumConcept

What are decorators in Python and how do they work?

Technology:
Python
Experience:
Mid-level,
Senior

Quick answer

A decorator is a function that takes another function and returns a modified version of it, letting you add behaviour such as logging, caching or access control without changing the original code.

Detailed explanation

The @decorator syntax is shorthand for func = decorator(func). A typical decorator defines an inner wrapper function that runs code before and after calling the original function, and returns that wrapper. Use functools.wraps so the wrapped function keeps its name and docstring.

Decorators rely on functions being first-class objects and on closures. Common built-in ones include @property, @staticmethod, @classmethod and functools.lru_cache. Frameworks use them heavily, for example @app.route("/") in Flask.

Example

python
import functools, time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
        return result
    return wrapper

@timed
def load_data():
    ...
  • PythonEasy

    What are *args and **kwargs in Python?

    *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, which lets a function accept a variable number of arguments.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    Why should you not use a mutable default argument in Python?

    Default argument values are evaluated once when the function is defined, so a default list or dictionary is shared between every call that does not pass its own, causing data to leak between calls.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    What are generators and the yield keyword in Python?

    A generator is a function that uses yield to produce values one at a time and remembers its state between calls, so it can process large or infinite sequences without holding everything in memory.

    Mid-level 路 Senior 路 Functions & Scope
  • PythonMedium

    What is the difference between @staticmethod and @classmethod in Python?

    A classmethod receives the class as its first argument (cls) and can create or configure instances, while a staticmethod receives no automatic argument and is just a function placed inside the class namespace.

    Junior 路 Mid-level 路 Object-Oriented Programming
  • PythonMedium

    How does Python manage memory and garbage collection?

    CPython frees objects mainly through reference counting, deleting an object as soon as nothing refers to it, and uses a cyclic garbage collector to clean up groups of objects that reference each other.

    Mid-level 路 Senior 路 Memory Management