第一种理解
contextmanager可以在核心代码的前面和后面补充执行代码
from contextlib import contextmanager
@contextmanager
def add_my_code():
print("i want eat ",end="")
yield
print(".",end="")
with add_my_code():
print("orange",end="")
# i want eat orange.
通过contextmanager装饰器和yield,该代码的执行流程为
可以结合Python 中 with 的使用分析一起理解。
另一种理解
from contextlib import contextmanager
class Myresource():
def query(self):
print("i queried data")
@contextmanager
def add_my_code():
print("before query")
yield Myresource()
print("ended query", end="")
with add_my_code() as r