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.
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():
passTo 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 rvApplying 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 fNow 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 - yTo 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 fHigher‑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 innerUsing it:
@ntimes(3)
def add(x, y):
print(x + y)
return x + yThis demonstrates that decorators can be stacked and combined to create powerful, reusable abstractions in Python.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
