Python Decorators Explained with Code Examples

⏱︎

Read time:

1–2 minutes
python-decorators

Introduction

Python decorators are a powerful design pattern that allows you to modify or extend the behavior of functions without changing their source code. They are widely used in frameworks like Flask and Django for routing, authentication, and logging.

What is a Decorator?

A decorator is a function that wraps another function, adding functionality before and/or after the wrapped function runs. The @ syntax is syntactic sugar for: func = decorator(func)

Your First Decorator

def my_decorator(func):

    def wrapper():

        print(‘Before the function runs’)

        func()

        print(‘After the function runs’)

    return wrapper

@my_decorator

def say_hello():

    print(‘Hello!’)

say_hello()

# Before the function runs

# Hello!

# After the function runs

Decorator with Arguments

import functools

def repeat(times):

    def decorator(func):

        @functools.wraps(func)

        def wrapper(*args, **kwargs):

            for _ in range(times):

                result = func(*args, **kwargs)

            return result

        return wrapper

    return decorator

@repeat(3)

def greet(name):

    print(f’Hello, {name}!’)

greet(‘Alice’)  # Prints 3 times

Practical Use Case – Timer Decorator

import time

import functools

def timer(func):

    @functools.wraps(func)

    def wrapper(*args, **kwargs):

        start = time.time()

        result = func(*args, **kwargs)

        end = time.time()

        print(f'{func.__name__} took {end-start:.4f}s’)

        return result

    return wrapper

@timer

def slow_function():

    time.sleep(1)

slow_function()  # slow_function took 1.0012s

Conclusion

This guide covered “Python Decorators Explained with Code Examples”. Bookmark this page and keep it as your go-to reference. If you found this helpful, share it with fellow developers and check out more snippets on programsnippet.com!

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version