上下文装饰器是既支持函数装饰又支持with语句的复合型装饰器,需同时实现__call__和__enter__/__exit__;与普通装饰器仅控制执行前后逻辑不同,它确保被装饰函数运行在特定上下文环境中,如自动管理资源或事务。

什么是上下文装饰器,和普通装饰器有什么区别
普通装饰器只控制函数执行前后的逻辑,而上下文装饰器需要让被装饰函数“运行在某个上下文环境里”——比如自动打开/关闭文件、切换数据库事务、临时修改线程局部变量。关键在于:它得支持 with 语句的进入(<strong>enter</strong>)和退出(<strong>exit</strong>)行为,同时还能作为函数装饰器使用。
这要求类同时实现:
- 可调用接口(
__call__),用于装饰函数 - 上下文管理接口(
__enter__/__exit__),用于with块
@MyContext() 装饰后,再写 with MyContext(): 就是两个独立实例,状态不共享。
用类实现带状态的上下文装饰器
最稳妥的方式是让装饰器返回一个可调用对象,该对象本身也支持上下文协议。典型结构是定义一个类,在 <strong>init</strong> 接收装饰器参数,在 <strong>call</strong> 返回一个包装函数;同时这个包装函数(或其内部对象)要能响应 with。
常见错误现象:TypeError: object does not support the context manager protocol,往往是因为返回的包装函数没实现 <strong>enter</strong>/<strong>exit</strong>。
立即学习“Python免费学习笔记(深入)”;
正确做法是让包装函数本身是一个支持上下文的类实例:
class timer:
def __init__(self, label=""):
self.label = label
<pre class="brush:php;toolbar:false;">def __call__(self, func):
def wrapped(*args, **kwargs):
# 这里不能直接写 with self: —— self 是装饰器实例,不是上下文实例
# 所以要构造一个新的上下文对象
ctx = _TimerContext(self.label)
with ctx:
return func(*args, **kwargs)
return wrappedclass _TimerContext: def init(self, label): self.label = label
def __enter__(self):
self.start = time.time()
print(f"[{self.label}] start")
def __exit__(self, *exc):
elapsed = time.time() - self.start
print(f"[{self.label}] done in {elapsed:.3f}s")
这样 @timer("db-query") 就能正常工作,且内部用 with _TimerContext(...) 确保上下文隔离。
用 contextlib.contextmanager 简化实现
如果不需要复杂状态或多次重入,用生成器 + @contextmanager 更轻量。但它不能直接当装饰器——得再包一层。
图片提示词生成器?不止如此。 马甲系统 —— 把脑海中的画面,翻译成AI能理解的专业表达。 用得越多,它越懂你:首次需要多问几句确认方向,用久了几乎一说就懂。 用得越多,它越快:缓存机制让后续对话越来越省。 RAG进化:成功案例持续入库,越跑越聪明。 输入「新手指南」查看完整功能介绍
容易踩的坑:@contextmanager 函数返回的是一个上下文管理器工厂,不是管理器本身;直接 @my_cm 会报 TypeError: 'generator' object is not callable。
正确组合方式:
- 定义一个
@contextmanager函数(如log_execution) - 再写一个装饰器函数,内部用
with log_execution():包裹原函数调用
from contextlib import contextmanager
<p>@contextmanager
def log_execution(name):
print(f"→ entering {name}")
yield
print(f"← leaving {name}")</p><p>def with_log(name):
def decorator(func):
def wrapped(*args, *<em>kwargs):
with log_execution(name):
return func(</em>args, **kwargs)
return wrapped
return decorator</p><h1>使用</h1><p>@with_log("cache-fetch")
def get_user(uid):
return {"id": uid, "name": "alice"}
这种写法清晰、易测,且 log_execution 本身还可单独用于 with 块,复用性高。
装饰器参数和上下文参数不一致怎么办
常见场景:想让装饰器接收配置(如超时秒数),但 with 块里还想动态传参(如具体重试次数)。这时不能只靠类初始化参数。
解决方案是让上下文对象接受运行时参数,而装饰器保留默认值:
class retry:
def __init__(self, max_attempts=3, delay=1):
self.default_max = max_attempts
self.default_delay = delay
<pre class="brush:php;toolbar:false;">def __call__(self, func):
def wrapped(*args, **kwargs):
# 允许调用时覆盖默认值:get_user(123, _retry=5)
attempts = kwargs.pop("_retry", self.default_max)
delay = kwargs.pop("_delay", self.default_delay)
ctx = _RetryContext(attempts, delay)
with ctx:
return func(*args, **kwargs)
return wrappedclass _RetryContext: def init(self, max_attempts, delay): self.max_attempts = max_attempts self.delay = delay
... enter/exit 实现重试逻辑
注意:参数名加下划线(如 _retry)是为了避免和被装饰函数本身的参数冲突,这是实际项目中容易忽略的细节。
装饰器逻辑越贴近真实调用链路,越容易暴露参数覆盖、作用域污染这类问题。别图省事把所有参数都塞进 <strong>init</strong>。

















