Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Decorators in Python

1. Introduction

Decorators in Python are a powerful and expressive way to modify the behavior of functions or methods. They allow you to wrap another function in order to extend its behavior without permanently modifying it.

2. What are Decorators?

A decorator is a function that takes another function as an argument, extends its behavior, and returns a new function. This is often used for logging, enforcing access control, instrumentation, and caching.

Note: Decorators are widely used in frameworks like Flask and Django for routes and middleware.

3. Creating Decorators

To create a decorator, define a function that takes a function as an argument, defines a nested function that modifies the behavior, and returns the nested function.


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()
        

4. Decorator Arguments

Sometimes you may want to pass arguments to your decorators. To achieve this, you need to create a decorator that returns another decorator.


def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                func(*args, **kwargs)
        return wrapper
    return decorator_repeat

@repeat(3)
def greet(name):
    print(f"Hello {name}")

greet("World")
        

5. Common Use Cases

  • Logging function calls
  • Access control and authentication
  • Memoization and caching
  • Timing function execution

6. Best Practices

Here are some best practices when working with decorators:

  1. Always use the built-in functools.wraps to preserve the original function's metadata.
  2. Keep decorators simple and focused on a single responsibility.
  3. Document decorators clearly, including their parameters and return values.
  4. Test decorators independently to ensure they behave as expected.

7. FAQ

What is the difference between a function and a method in Python?

A function is a block of code that is designed to perform a particular task. A method is a function that is associated with an object and can access its data.

Can decorators be applied to classes?

Yes, decorators can also be applied to classes to modify their behavior, similar to how they modify functions.

How do decorators handle arguments?

To handle arguments in decorators, you create a decorator that returns another decorator function, allowing the nested function to accept the arguments.