Huzi Blogs
Blog
Blog
Disclaimer & Data Privacy Policy
Project by huzi.pk

© 2026 blogs.huzi.pk. All Rights Reserved.

    Back to all posts
    Programming

    Mastering Python Decorators: A Practical Guide

    By Huzi

    Python decorators are a powerful feature that can seem intimidating at first, but they are an essential tool for any serious Python developer. They allow you to modify the behaviour of a function or class without permanently changing its source code.

    In simple terms, a decorator is a function that takes another function and extends its behaviour without explicitly modifying it.

    The Anatomy of a Decorator

    At its core, a decorator is just a function that returns a wrapper 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()
    

    Output:

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

    Practical Use Cases

    1. Timing Functions

    One of the most common uses is to measure how long a function takes to execute—great for optimization.

    import time
    
    def timer(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            end = time.time()
            print(f"{func.__name__} ran in {end - start}s")
            return result
        return wrapper
    
    @timer
    def heavy_computation():
        sum(range(1000000))
    
    heavy_computation()
    

    2. Authentication & Logging

    In web frameworks like Flask or Django, decorators are used extensively for checking if a user is logged in.

    def login_required(func):
        def wrapper(user):
            if not user.is_logged_in:
                return "Please log in first!"
            return func(user)
        return wrapper
    

    3. Memoization (Caching)

    Decorators can cache the results of expensive function calls so that the next time the function is called with the same arguments, the result is returned instantly.

    from functools import lru_cache
    
    @lru_cache(maxsize=None)
    def fibonacci(n):
        if n < 2:
            return n
        return fibonacci(n-1) + fibonacci(n-2)
    

    Why Use Them?

    • Clean Code: They separate core logic (the function) from auxiliary logic (logging, timing, auth).
    • Reusability: You can write a decorator once and apply it to dozens of functions.
    • Readability: Seeing @login_required above a function immediately tells you it's a protected route.

    Conclusion

    Decorators are a hallmark of "Pythonic" code. By mastering them, you write cleaner, more efficient, and more professional applications. Start experimenting with simple wrapper functions, and soon you'll be writing your own custom decorators for everything!

    Advertisements


    You Might Also Like

    Digital Print Karandi Unstitched Winter 3-Piece Suit – Thread Embroidery

    Digital Print Karandi Unstitched Winter 3-Piece Suit – Thread Embroidery

    PKR 5000

    Luxurious Handwork Embroidered Chiffon Bridal Frock (40" L) | Emb. Silk Trouser

    Luxurious Handwork Embroidered Chiffon Bridal Frock (40" L) | Emb. Silk Trouser

    PKR 9600

    Maroon Embroidered NET Bridal Sharara Dress – Unstitched Luxury Party & Wedding Outfit with Rich Neckline

    Maroon Embroidered NET Bridal Sharara Dress – Unstitched Luxury Party & Wedding Outfit with Rich Neckline

    PKR 14500

    Luxury Handwork Heavy Embroidered Net & Masoori Bridal Maxi 2026

    Luxury Handwork Heavy Embroidered Net & Masoori Bridal Maxi 2026

    PKR 8899

    Luxury Heavy Embroidered Velvet & Net Bridal Saree 2026

    Luxury Heavy Embroidered Velvet & Net Bridal Saree 2026

    PKR 8800

    Advertisements


    Related Posts

    Programming
    Building a REST API with Node.js and Express
    Learn how to build a robust and scalable REST API from scratch using Node.js and the Express framework. This guide covers routing, middleware, and connecting to a database.

    By Huzi

    Read More
    Programming
    C# Essential Guide to Modern Programming Techniques
    C# is a versatile programming language from Microsoft, running on the .NET platform. It supports multiple programming styles and is used to build a wide range of applications, including web, desktop, mobile, and games. It is known for its clear syntax and strong typing.

    By Huzi

    Read More
    Programming
    The Ultimate Beginner's Guide to Building a Website with Cloudflare Pages
    This guide provides a comprehensive walkthrough for deploying a modern website on Cloudflare Pages, covering everything from Git setup and local development to serverless functions, security, and monitoring.

    By Huzi

    Read More
    Legal
    How to Report a Fake Bank Transaction in Pakistan (2025 Edition)
    Step-by-step paths for reporting fake bank transactions to the State Bank (SBP), Banking Mohtasib, and your bank. Updated for 2025.

    By Huzi

    Read More
    Music
    BTS World Tour 2026: The Purple Reign Reunion ARMY Guide
    BTS returns in 2026! Everything you need to know about the 'Purple Reign' World Tour and the new album.

    By Huzi

    Read More
    Technology
    The 5-Second Boot: Optimizing Arch Linux Performance (2025)
    Is your Arch Linux system taking too long to start? Learn how to use systemd-analyze to find bottlenecks and optimize your boot time for a lightning-fast experience.

    By Huzi

    Read More