table of Contents
Understanding and using the context manager Python
What is the context manager?
- Manager is a context object wrapper arbitrary code block.
- The context manager ensure access to context manager, every time the code consistency of execution.
- When you exit the context manager, related resources can be properly recycled.
Simply put context manager is with 语句
The benefits of using a context manager
-
It may be in a more elegant way, the operation (create / acquire / release) resources, such as file operations, database connection;
-
Must be able to ensure the implementation of exit steps, with statements by writing code, make the code more concise, do not go to close the file.
-
It may be in a more elegant way to handle exceptions.
Use the context manager
To achieve their management of such a context, you must first know the context management protocol.
Simply put, that is in a class, instance of this class is a context manager.实现了 enter 和__exit__的方法
# 上下文管理协议
class Sample:
def __enter__(self):
print("enter")
# 获取资源
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# 释放资源
print("exit")
def do_something(self):
print("doing something")
with Sample() as sample:
sample.do_something()
Output:
enter
doing something
exit
Can clearly be seen from this example, when writing code, or can be acquired in connection __enter__ resources, and the resource is written off in the __exit__.
contextlib simplified context manager
# 让普通函数也可以使用上下文管理, 前提条件是add函数必须是生成器函数,且只有yield语句
from contextlib import contextmanager
@contextmanager
def add(x, y):
print('__enter__') # 第一步:调用__enter__
yield x + y # 第二步:返回__enter__函数的返回值给obj对象
print('__exit__') # 第四步:调用__exit__
with add(1, 2) as obj:
print(obj) # 第三步:执行上下文语句块
Output:
__enter__
3
__exit__
- contextlib Python standard library module is to provide a more user-friendly context management tool module;
- It is implemented by the decorator, do not need to create a class and use __enter__ and __exit__ these two methods, it is more convenient than with the statement;
- @contextmanager is a decorator decorator, generator which receives a generator, the generator in the yield with the value assigned to the variable ... as, and performed with a normal sentence;
- closing after @contextmanager also a decorative decorator, closing () can become the object context object, then use the with statement (provided that this object can call close () method!);
Reference: context manager