Sitemap

Python: Decorating Code with Decorators

4 min readMay 19, 2023

--

Press enter or click to view image in full size
Photo by freestocks on Unsplash

What is a decorator in Python?

Python decorators are a versatile and powerful tool that can greatly enhance the functionality of code. A decorator is a design pattern that allows developers to change the behavior of a function or class without directly modifying its source code. It is a higher-order function and class, which receives a function or class as an input and returns it with added modifications or improvements. Decorators enable developers to wrap another function, extending the behavior of the wrapped function, without permanently altering it. To better our understanding of decorators, we first must discuss the concept of functions being first class objects in Python.

Python Functions are First Class Objects

In Python, functions are considered first class objects which means that functions have the following properties:

  • are instances of the Object type
  • can be stored in a variable
  • used or passed as parameters to other functions
  • can return functions from other functions
  • can store them in data structures

Function Decorators

def example_decorator(func):
def wrapper(name):
print("This is before function execution...")
result = func(name)
print("This is after function execution...")
return result
return wrapper

@example_decorator
def greet(name):
print(f"Hello, {name}!")

greet("Joe")

As shown above, decorators are denoted by the “@decorator_name” syntax placed above function declarations. When the decorated function is called, it is actually the modified version provided by the decorator that gets executed.

Before function execution
Hello, John!
After function execution

Chaining

In Python, decorators can be chained, allowing developers to apply multiple decorators to a single function in a sequential manner. Each decorator adds its own functionality or modifications to the function.

def stars(func):
def inner(*args, **kwargs):
print("*" * 20)
func(*args, **kwargs)
print("*" * 5)
return inner

def dashes(func):
def inner(*args, **kwargs):
print("-" * 15)
func(*args, **kwargs)
print("-" * 10)
return inner

@stars
@dashes
def printer(msg):
print(msg)

printer("Hello")

The decorators @stars and @dashes both modify the original printer function. Initially, the stars decorator is applied first by printing 20 stars then calls the inner function within the dashes function, consequently printing 15 dashes. Then, the original function prints the word “Hello” passed as a parameter which then calls the following print function from the inner function of dashes, printing the next 10 dashes. Lastly, the following print function from the inner function of stars is invoked, printing the last 5 stars.

******************** # 20 stars
--------------- # 15 dashes
Hello # "Hello"
---------- # 10 dashes
***** # 5 stars

Class Decorators

Decorators can also be used in the context of classes, also allowing developers to modify or enhance the behavior of a class by wrapping it with another class. In a similar fashion as function decorators, you use the “@decorator_name” syntax above the class declaration. Then, a decorator function takes the original class as an argument and returns a new class with added modifications.

def decorator(cls):
# Define a new class that extends the original class
class DecoratedClass(cls):
# Add a new attribute
new_attribute = "This is an added attribute"

# Create a new method
def new_method(self):
print("This is a new method")

# Override an existing method
def original_method(self):
super().existing_method()
print("This is an enhanced existing method")

# return the new decorated class
return DecoratedClass

# Use the @ syntax to add the decorator
@decorator
class OriginalClass:
def original_method(self):
print("This is the original method")

# Create an instance of the decorated class
instance = OriginalClass()

print(instance.new_attribute) # Print the newly created attribute
instance.new_method() # Execute the newly created method
instance.original_method() # Call the existing and enhanced method

The code above would output the following:

This is an added attribute
This is a new method
This is the original method
This is an enhanced existing method

Class decorators are extremely useful since it allows to add new functionality to existing classes without directly altering its source code.

Get Halim Choi’s stories in your inbox

Join Medium for free to get updates from this writer.

Use Cases for Decorators

The following are just some of the many use cases for decorators:

  • error handling: handle error logic across multiple functions
  • logging: add logging functionality to track and record execution of certain code segments
  • timing: measure execution time of functions
  • validation: validate inputs or outputs and ensure conditions or constraints are met
  • limiting: limit API rate to prevent overuse

By leveraging the concept of functions as first-class objects, decorators enable the modification and extension of functions and classes through a simple and elegant syntax. Whether it’s adding additional behavior, chaining multiple decorators, or enhancing existing classes, decorators provide flexibility and reusability in code design.

Here are some helpful sources to learn more about Python Decorators:

--

--