DEV Community

Aishwarya Raj
Aishwarya Raj

Posted on

3 1

Python Decorators: Adding Magic to Your Functions, One Layer at a Time

What Exactly is a Decorator?

A decorator in Python is a powerful tool that allows you to wrap extra functionality around an existing function. Think of it as putting an extra layer of “awesome” on a function, without actually changing the original code.


How Decorators Work

A decorator is simply a function that takes another function as input, adds some extra functionality, and returns a new function.

Example:

def shout(func):
    def wrapper():
        return func().upper()
    return wrapper

@shout
def greet():
    return "hello"

print(greet())  # Outputs: HELLO
Enter fullscreen mode Exit fullscreen mode

Here, the @shout decorator transforms greet() so it returns its output in uppercase.


Common Use Cases for Decorators

Decorators are handy for adding cross-cutting functionalities to functions, like:

  • Logging: Automatically logging whenever a function is called.
  • Authentication: Checking permissions before running sensitive functions.
  • Timing: Measuring how long a function takes to run.

Stacking Decorators

Yes, you can stack multiple decorators to apply multiple layers of functionality to a single function.

@authenticate
@log
def process_data(data):
    # Function code
Enter fullscreen mode Exit fullscreen mode

This runs authenticate first, then log, and finally process_data.


Final Words: Decorators—Your Function’s Best Friend

Decorators let you add power to your code without clutter. They’re your shortcut to clean, reusable, and enhanced functions.

🥂 Here’s to functions that do more, without the mess!"

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more