I talked about how to define a context manager protocol (with statement) in this blog. Today I want to talk about a simpler way to define it.
python
Provides a built-in module contextlib
with a decorator that @contextlib.contextmanager
can turn a function into a context manager.
import contextlib
@contextlib.contextmanager
def file_open(file_name): #此处只是模拟并没有真的打开一个文件
print("file open")
yield {
} # 把函数变为生成器
print("file end")
In fact, the yield
above logic is equivalent to the logic in the __enter__
function in the previous blog (acquiring resources), and the yield
following logic is equivalent to the __exit__
function in that blog (releasing resources).
yield
The logic can be arbitrary. This function becomes a context manager.
Then use the with
statement.
with file_open("bobby.txt") as f_open: #只是模拟,说明逻辑,没有真的文件
print("file processing")
#输出为
# file open
# file processing
# file end
When running, first enter the __enter__
function, that is, the yield
above code, print file open
, then run the print file processing
, and finally enter the __exit__
function, that is, run the yield
following code, print file end
.