Decorators
Transform 函数使用 decorators: @ 语法, functools.wraps, and practical decorator 模式.
你将学到
- 理解函数 as 首先-类对象
- 编写 and apply decorators 使用 @ 语法
- Use functools.wraps 到 preserve metadata
- 创建 decorators 使用实参
- Apply practical decorator 模式
概念讲解
Functions Are Objects
In Python, functions are first-class objects — they can be assigned to variables, passed as arguments, and returned from other functions. This is the foundation of decorators:
def greet(name):
return f"Hello, {name}!"
say_hello = greet # assign function to a variable
print(say_hello("Ada")) # Hello, Ada!
def call_twice(func, value):
return func(value) + " " + func(value)
print(call_twice(greet, "Ada")) # Hello, Ada! Hello, Ada!
Because functions are objects, you can write functions that modify other functions. A decorator is exactly that — a function that takes a function and returns a new (wrapped) function.
Basic Decorator
def uppercase_result(func):
def wrapper():
result = func()
return result.upper()
return wrapper
def greet():
return "hello, 世界!"
greet = uppercase_result(greet) # manually decorate
print(greet()) # HELLO, WORLD!
The decorator uppercase_result takes greet, and returns a new wrapper function that calls greet and uppercases the result. The original greet is replaced by the wrapped version.
The @ Syntax
The @ symbol is syntactic sugar for applying a decorator:
@uppercase_result
def greet():
return "hello, 世界!"
# This is exactly equivalent to:
# def greet():
# return "hello, 世界!"
# greet = uppercase_result(greet)
print(greet()) # HELLO, WORLD!
The @decorator line above a function definition applies the decorator immediately after the function is defined. This is the standard way to use decorators.
Decorators with Arguments
To pass arguments to the decorator itself, you need an extra level of nesting:
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result * n
return wrapper
return decorator
@repeat(3)
def greet(name):
return f"Hello, {name}! "
print(greet("Ada")) # Hello, Ada! Hello, Ada! Hello, Ada!
repeat(3) returns a decorator, which wraps the function. The *args, **kwargs in wrapper ensures the wrapped function accepts any arguments.
functools.wraps — Preserve Metadata
When you wrap a function, the wrapper replaces the original's __name__, __doc__, and other metadata. Use functools.wraps to preserve them:
from functools import wraps
def log_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}({args}, {kwargs})")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_calls
def add(a, b):
"""添加 two 数字."""
return a + b
print(add.__name__) # 'add' (preserved by @wraps)
print(add.__doc__) # 'Add two numbers.' (preserved)
print(add(2, 3))
# Calling add((2, 3), {})
# add returned 5
# 5
Always use @wraps(func) in your decorators — without it, debugging becomes harder because all wrapped functions show up as wrapper instead of their real names.
Practical Decorator: Timing
import time
from functools import wraps
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return result
return wrapper
@timed
def slow_function():
time.sleep(1)
return "做"
slow_function() # slow_function took 1.0012s
Stacking Decorators
You can apply multiple decorators — they are applied bottom-up:
@decorator_a
@decorator_b
def func():
pass
# Equivalent to: func = decorator_a(decorator_b(func))
The decorator closest to the function is applied first. decorator_b wraps func, then decorator_a wraps the result.
Built-in Decorators
Python has several built-in decorators you will encounter:
@staticmethod/@classmethod— in classes@属性— computed attributes@functools.lru_cache— memoization (cache results)@dataclass— auto-generate class boilerplate
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(100)) # fast — results are cached
@lru_cache is one of the most useful built-in decorators — it caches function results to avoid recomputation, turning an exponential Fibonacci into a linear one.
示例代码
import time
from functools import wraps
# Basic decorator
def uppercase_result(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@uppercase_result
def greet(name):
"""Greet someone."""
return f"hello, {name}!"
print(greet("Ada")) # HELLO, ADA!
print(greet.__name__) # greet (preserved by @wraps)
# Decorator with arguments
def repeat(n):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs) * n
return wrapper
return decorator
@repeat(3)
def say(word):
return word + " "
print(repr(say("Hi"))) # 'Hi Hi Hi '
# Practical: timing decorator
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f" {func.__name__} took {elapsed:.6f}s")
return result
return wrapper
@timed
def compute():
total = sum(x ** 2 for x in range(10000))
return total
print(f"Result: {compute()}")
# Built-in: lru_cache for memoization
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(f"Fibonacci(30) = {fibonacci(30)}") # fast — cached
# Stacking decorators
@uppercase_result
@timed
def get_message():
return "hello from the function"
print(get_message())
Shows 基础 decorator 使用 @wraps, decorator factory 使用实参, practical timing decorator, 构建-in @lru_cache for memoization, and stacked decorators applied 底部-上.
动手试一试
- JSON Formatter
Decorators 是 used in web 框架到 格式 JSON 响应.
- Regex Tester
Decorators 能缓存 compiled regex 模式 for 性能.
常见错误
错误写法
Forgetting @wraps(func) and losing 原始函数's name and docstring
正确做法
不使用 @wraps, wrapped 函数's __name__ becomes 'wrapper' and __doc__ 是 lost, 制作调试 and help() useless. 总是 use @functools.wraps(func) on wrapper 函数内部你的 decorator.
错误写法
不 using *args, **kwargs in wrapper, 所以它 仅工作使用否-实参函数
正确做法
wrapper 必须接受 *args, **kwargs and 通过它们通过到 func(*args, **kwargs). 不使用这个, decorator 仅工作 on 函数使用否 参数, limiting 它的 usefulness.
相关资源
相关速查表
- Python Cheatsheet
Decorator 语法, @wraps, and 常见 decorator 模式.
练习 Decorators
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。