The independent file on technology, travel & lifeFrom Pakistan, for everywhere
Huzi Blogs.
The ArchiveSectionsSearch

Planning a trip? HTG Travels — flights, visas, hotels & Umrah, handled properly.

WhatsApp +92 317 5054959
Huzi Blogs.

An independent file on technology, travel and life — long-form guides written plainly, from Pakistan, for everywhere.

ShopMeet the Creator

Sections

  • Travel
  • Technology
  • Lifestyle
  • Programming
  • Sports
  • Linux
  • All sections

The Desk

  • The Archive
  • Search the file
  • Disclaimer & Data Privacy Policy
  • A project of huzi.pk

© 2026 blogs.huzi.pk — All rights reserved.

Set in Playfair Display & Inter

    HomePythonStory
    Python

    Mastering Python Decorators: A Practical Guide (2026)

    H

    By Huzi

    File #299 · 3 min read

    Python decorators are essential components of modern frameworks like FastAPI and Pydantic, forming the grammar of the Python ecosystem—every route begins with an @ line, and understanding them unlocks half of your favourite framework's documentation.

    The quick answer: A decorator is a function that takes a function and returns a wrapper that does a little extra work around it. Add functools.wraps every time, learn the factory layer for arguments, lean on the stdlib before hand-rolling, and type it all with ParamSpec.

    The anatomy: a function that returns a wrapper

    A decorator is just a function that returns a wrapper — it takes a function and hands back a new one that does a little extra work around it:

    from functools import wraps
    
    def log_calls(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print(f"Calling {func.__name__}")
            result = func(*args, **kwargs)
            return result
        return wrapper
    
    @log_calls
    def say_hello(name: str) -> str:
        """Greet someone by name."""
        return f"Hello, {name}!"
    

    Factories: decorators that take arguments

    The pattern that confuses everyone — a decorator with parameters — is one more layer: a function that returns a decorator.

    from functools import wraps
    
    def require_role(role: str):
        def decorator(func):
            @wraps(func)
            def wrapper(user, *args, **kwargs):
                if role not in user.roles:
                    raise PermissionError(f"Requires role: {role}")
                return func(user, *args, **kwargs)
            return wrapper
        return decorator
    

    That is the entire trick behind @app.get("/hello") and @retry(times=3). Once you see the extra layer as just another function call, the panic stops.

    Do not hand-roll what the stdlib ships

    For caching, functools.cache handles the unbounded case and functools.lru_cache(maxsize=128) bounds it — a memoised fibonacci runs instantly with two lines. For retries with exponential backoff against a flaky API, tenacity is more robust than anything you will write in an afternoon.

    Write your own decorators for the things specific to your codebase — audit logging, permission checks, timing — and use the batteries for the generic jobs.

    The job The tool
    Keep the wrapper honest functools.wraps
    Unbounded caching functools.cache
    Bounded caching functools.lru_cache(maxsize=128)
    Retries with exponential backoff tenacity
    Typed decorators ParamSpec

    Typing them properly

    Untyped decorators erase signatures from the type checker's view. The modern fix is ParamSpec, and it is what the large libraries do internally:

    from typing import Callable, ParamSpec, TypeVar
    from functools import wraps
    
    P = ParamSpec("P")
    R = TypeVar("R")
    
    def log_calls(func: Callable[P, R]) -> Callable[P, R]:
        @wraps(func)
        def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            return func(*args, **kwargs)
        return wrapper
    

    This keeps full autocompletion alive through the wrapper — the difference between a decorator your team enjoys and one they quietly delete.

    When not to write one

    A decorator should earn its layer. If the wrapper adds nothing a plain function call could, skip it — flat beats nested applies to decorators most of all. The best decorator is the one a reader forgets is there.

    If you use tenacity against a flaky API, you already understand airline systems: attempt, back off, attempt again. HTG Travels runs that retry loop behind every itinerary — seats, hotels, visas — so the caller never sees the exceptions. And the mountains do not care about your stack trace; that is their entire medical value.

    Pro tip: Copy @wraps(func) every time, no exceptions. Without it the wrapped function loses its name, docstring and signature — which quietly breaks documentation tools and IDE introspection.

    In Gaza, neighbours and paramedics wrap the injured in whatever cloth survives the night and keep working — the oldest protection layer there is, running on no framework at all, and may it hold.

    When your head is full of wrappers, the cure is a place with none. HTG Travels runs weekend escapes out of Sialkot — Swat and Kalam itineraries, drivers who know the road, hotels confirmed in writing before you leave. Call +92 317 5054959 when the deploy can wait and the mountains cannot.

    Presented by

    HTG Travels — Plan the Trip, Skip the Runaround

    Flights, visas, Umrah packages and Hunza–Skardu tours, handled end to end from our licensed Sialkot desk. Real fares, hotel names in writing, and a human who answers — before you pay a rupee.

    Flights & rebooking Visa files Umrah 2026–27 Northern tours
    Visit huzi.pkWhatsApp +92 317 5054959

    Sialkot, Pakistan · Licensed agency · Fast quotes on WhatsApp


    You Might Also Like

    Elegant Swiss Lawn 3-Pc Suit with Heavy Embroidered Patches & Digital Silk Dupatta

    Elegant Swiss Lawn 3-Pc Suit with Heavy Embroidered Patches & Digital Silk Dupatta

    PKR 4600

    Ivory Organza Wedding Dress – Heavy Handwork, Aqua Net Dupatta

    Ivory Organza Wedding Dress – Heavy Handwork, Aqua Net Dupatta

    PKR 8000

    Printed & Embroidered Lawn Suit 3-Pc | Border Embroidered Soft Chiffon Dupatta (2025)

    Printed & Embroidered Lawn Suit 3-Pc | Border Embroidered Soft Chiffon Dupatta (2025)

    PKR 5300

    All-Over Print Embroidered Lawn Suit 3-Pc (2025) | 4-Side Embroidered Chiffon Dupatta

    All-Over Print Embroidered Lawn Suit 3-Pc (2025) | 4-Side Embroidered Chiffon Dupatta

    PKR 4900

    Heavy Handwork Embroidered Chiffon Suit (Navy Blue) | Wedding Wear

    Heavy Handwork Embroidered Chiffon Suit (Navy Blue) | Wedding Wear

    PKR 5700

    Keep reading

    Related files

    Python
    English

    The Serpent's Grace: The Ultimate Python 3.13 Guide (2026)

    The practice-path way to learn Python: a project ladder from a script that saves you an hour to a deployed AI agent, plus the 2026 tooling — uv, ruff, pyright, pytest — that keeps the climb sane.

    By HuziFile #421

    Read
    Python
    English

    Getting Started with Python 3.13 for Absolute Beginners (2026)

    The strict quickstart: install Python 3.13 properly (including the Windows PATH trap), write and run your first script today, and know exactly what to learn in what order next.

    By HuziFile #191

    Read
    Python
    English

    Introduction to Python 3.13: The All-Purpose Language (2026)

    What Python actually is: an interpreted, whitespace-sensitive language whose readable syntax now runs everything from Sunday scripts to the AI stack, with 3.13's speed work humming under the hood.

    By HuziFile #280

    Read
    Python
    English

    Automate the Boring Stuff with Python: 3 Modern Scripts (2026)

    The three scripts worth keeping: a pathlib file organizer, an async httpx scraper, and a bulk image resizer with Pillow — real code, modern Python 3.15, tested shapes.

    By HuziFile #48

    Read
    Programming
    English

    A Beginner's Guide to React Hooks: Mastering Modern React (2026)

    useState, useEffect, the React 19 form hooks, and the two rules that keep hooks from breaking — each with a runnable snippet.

    By HuziFile #10

    Read
    Programming
    English

    Python Testing Pyramid 2026: The Complete Problem-Solving Guide

    The 70/20/10 pyramid in practice — pytest fixtures and parametrize, boundary mocking, Hypothesis, testcontainers, and the CI loop your team can actually trust.

    By HuziFile #560

    Read
    Back to the archive