Skip to main content

📝 Latest Blog Post

Wrapping Up Your Functions: A Guide to Python Decorators

Wrapping Up Your Functions: A Guide to Python Decorators

As you become more proficient in Python, you'll encounter a powerful and elegant concept called a **decorator**. A decorator is a design pattern that allows you to add new functionality to an existing function or class without permanently modifying its code. Think of it as a "wrapper" that you place around a function, adding extra features like logging, timing, or authentication before the original function is even called. Understanding decorators is a key step toward writing cleaner, more scalable, and more reusable code. 🎁

The Decorator in a Nutshell

At its core, a decorator is just a function that takes another function as an argument, and returns a new, modified function. The syntax for applying a decorator is the `@` symbol, followed by the decorator's name, placed on the line immediately before the function you want to decorate.

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

When you run this code, the `say_hello()` function is wrapped by `my_decorator`. The output will be:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

The `wrapper` function inside our decorator is where all the magic happens. It performs the new functionality and then calls the original function (`func()`).

Common Uses of Decorators

Decorators are used in many parts of the Python ecosystem, especially in web frameworks like Flask and Django. Common use cases include:

  • Logging: A decorator can log a message every time a function is called.
  • Timing: A decorator can measure how long it takes for a function to execute.
  • Authentication: A decorator can check if a user is logged in before allowing them to access a specific function or web page.

By understanding decorators, you unlock a new level of control over your functions and can write code that is both more powerful and more elegant.

Comments

🔗 Related Blog Post

🌟 Popular Blog Post