A Dive Into Python Decorators

Introduction

One of the great, powerful features in Python is decorators. Python decorators are a specific change to the Python syntax that allows you to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.

What is a decorator?

In Python, a decorator is a callable that takes a function as an argument and returns a replacement for that function. A "callable" is anything that can be called. This could be a function, method, class or instance.

Let's go deeper and explore the practical side.

First, we start by understanding a simple function in Python:

def greet(name): return f"Hello {name}" print(greet("World"))

This Python function greet(), takes a name and return a string.

Now, let's create our first basic decorator:

def uppercase_decorator(function): def wrapper(): func = function() make_uppercase = func.upper() return make_uppercase return wrapper

Here, we defined uppercase_decorator() function which takes a function function and defines another function wrapper() inside it. The wrapper() function will convert the output of the original function to uppercase. The uppercase_decorator() function returns the reference of this newly created function wrapper().

Let's apply this decorator to our greet() function:

def greet(name): return f"Hello {name}" decorated_greet = uppercase_decorator(greet) print(decorated_greet())

Great! But this is not the standard/correct way to apply a decorator to a function. Python provides a more readable and more common way to apply decorator. Let’s see below how we can do that:

@uppercase_decorator def greet(name): return f"Hello {name}" print(greet("World"))

In line 1, the @uppercase_decorator is a decorator that we have already defined in the previous step.

Decorators are a significant part of Python; however, they can be challenging for beginners. Start by understanding Python's functions from inside out, their features, and then gradually start using decorators. Practise is key when learning a new concept; thus, begin by writing basic decorators and move towards creating complex ones gradually.

I hope with this blog post, you are now more confident in understanding and writing your Python decorators.