Fundamentals 9 min read

Master Python Decorators: From Basics to Advanced Usage

This article explains Python decorators by first reviewing functions as first‑class objects, then showing how to create simple timing decorators, extend them with *args/**kwargs, and build higher‑order decorators like a repeat‑n‑times wrapper, complete with practical code examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Decorators: From Basics to Advanced Usage

In Python, functions are flexible objects that can be assigned to variables, passed as arguments, or returned from other functions. A decorator is essentially a function that adds functionality to another function without modifying its code.

Using the @ syntax sugar, a decorator can wrap a target function. For example:

@dec
def func():
    pass

To illustrate, consider a simple addition function add(x, y=10). By inspecting its attributes (e.g., __name__, __module__, __defaults__), we see that functions carry metadata and can be examined with the inspect module.

A basic timer decorator measures execution time:

from time import time

def timer(func, x, y=10):
    before = time()
    rv = func(x, y)
    after = time()
    print('time taken:', after - before)
    return rv

Applying this decorator manually requires wrapping each function, which becomes cumbersome when multiple functions need the same behavior.

By returning a wrapper function, we can create a reusable decorator:

def timer(func):
    def f(x, y=10):
        before = time()
        rv = func(x, y)
        after = time()
        print('time taken:', after - before)
        return rv
    return f

Now add = timer(add) and sub = timer(sub) automatically gain timing functionality.

Using the @ syntax makes the code cleaner:

@timer
def add(x, y=10):
    return x + y

@timer
def sub(x, y=10):
    return x - y

To handle arbitrary arguments and keyword arguments, the decorator can be written with *args and **kwargs:

def timer(func):
    def f(*args, **kwargs):
        before = time()
        rv = func(*args, **kwargs)
        after = time()
        print('time taken:', after - before)
        return rv
    return f

Higher‑order decorators can be built to add more complex behavior. For example, a decorator that repeats a function n times:

def ntimes(n):
    def inner(f):
        def wrapper(*args, **kwargs):
            for _ in range(n):
                rv = f(*args, **kwargs)
            return rv
        return wrapper
    return inner

Using it:

@ntimes(3)
def add(x, y):
    print(x + y)
    return x + y

This demonstrates that decorators can be stacked and combined to create powerful, reusable abstractions in Python.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythondecoratorstimerargskwargshigher-order
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.