Master Python Decorators: Concepts, Usage, and Design Patterns
This article explains what Python decorators are, their key characteristics, how to pass arguments, stack multiple decorators, use built‑in decorators from the standard library such as @property and @wraps, and relates decorator functions to the classic decorator design pattern, all illustrated with clear code examples.
Reference
Books: Fluent Python , Effective Python
Basic Concepts
Question 1: What is a decorator?
Answer: A decorator is syntactic sugar; it is a callable object that takes a function as an argument and returns a callable, often replacing the original function.
Question 2: What are the features of decorators?
Answer: Decorators can replace the decorated function with another function and can execute code at module load time.
def decorate(func):
print('running decorate', func)
return func()
def decorate_inner():
print('running decorate_inner function')
return func()
return func
return decorate_innerQuestion 3: How to use arguments of the decorated function?
Answer: Pass arguments via *args and **kwargs in the wrapper.
def decorate(func):
def decorate_inner(*args, **kwargs):
print(type(args), type(kwargs))
print('args', args, 'kwargs', kwargs)
return func(*args, **kwargs)
return decorate_innerStacked Decorators
Question: What is the execution order of stacked decorators?
Answer: The innermost decorator is applied first; the function is wrapped by the inner decorator, producing a new function that is then wrapped by the outer decorator.
def outer(func):
print('enter outer', func)
def wrapper():
print('running outer')
func()
return wrapper
def inner(func):
print('enter inner', func)
def wrapper():
print('running inner')
func()
return wrapper
@outer
@inner
def main():
print('running main')
if __name__ == '__main__':
main()Standard Library Decorators
Common built‑in decorators include @property, @classmethod, @staticmethod, and those from functools such as lru_cache, singledispatch, and wraps.
from functools import lru_cache, singledispatch, wrapsWhy use @wraps ? It copies important metadata (e.g., __name__, docstring) from the original function to the wrapper, preventing side effects that break introspection tools.
from functools import wraps
def decorate(func):
@wraps(func)
def decorate_inner():
print('running decorate_inner function')
return func()
return decorate_innerDecorator Design Pattern
The design pattern adds responsibilities to objects dynamically, keeping the component and decorator interfaces identical so that clients can use them transparently; multiple decorators can be nested to compose behavior.
Python decorators implement the same idea but are more powerful and not a one‑to‑one mapping to the classic pattern.
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.
