← All questions
Python & DataMedium· OOP & Advanced Python

What are decorators in Python, and what do they actually get used for in production ML code?

A decorator sits above a function and wraps it, adding behavior — timing it, retrying it, caching its result — without modifying the function’s own code. The value is separation of concerns: the retry logic doesn’t belong tangled inside your training loop, and a decorator lets you add it as a layer instead.

The one that matters most in production GenAI code is a retry decorator with exponential backoff wrapped around LLM and embedding API calls — those calls fail intermittently for reasons that have nothing to do with your code, and a pipeline with no retry logic crashes on the first transient timeout. A timing decorator around training or inference steps is the next most common, useful for spotting regressions without littering time.time() calls everywhere. functools.lru_cache applied to an expensive, repeatable computation — embedding the same piece of text twice, say — avoids redoing work for free. All three follow the same shape: *args, **kwargs pass straight through, so the decorator works on any function regardless of its signature.

Code playground (Python)