The contextlib module in Python

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.

pythonProvides a built-in module contextlibwith a decorator that @contextlib.contextmanagercan 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 yieldabove logic is equivalent to the logic in the __enter__function in the previous blog (acquiring resources), and the yieldfollowing logic is equivalent to the __exit__function in that blog (releasing resources).

yieldThe logic can be arbitrary. This function becomes a context manager.

Then use the withstatement.

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 yieldabove code, print file open, then run the print file processing, and finally enter the __exit__function, that is, run the yieldfollowing code, print file end.

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106954854