Context Management Protocol: Contains the methods __enter__()
and __exit__()
, and objects that support this protocol must implement these two methods.
Context Manager: An object that supports the context management protocol. This object implements the methods __enter__()
and __exit__()
.The context manager defines the runtime context to be established when executing the with statement, and is responsible for executing the entry and exit operations in the context of the with statement block.A context manager is usually invoked using the with statement, but can also be used by calling its methods directly.
After talking about the above two concepts, let's start with the common expressions of the with statement, a basic with expression whose structure is as follows:
with EXPR as VAR:BLOCK
where EXPR can be any expression; as VAR is optional.The general execution process is as follows:
__exit()__
method of the context manager and save it for later calls;__enter__()
method of the context manager; if the as clause is used, assign the return value of the __enter__()
method to the as clauseVAR;__exit__(
) method of the context manager is executed, and the __exit__()
method is responsible for performing "cleanup" work, such as releasingresources, etc.If no exception occurs during execution, or the statement break/continue/return is executed in the statement body, __exit__(None, None, None)
is called with None as a parameter; if an exception occurs during execution,Then use the exception information obtained by sys.exc_info as the parameter to call __exit__(exc_type, exc_value, exc_traceback)
;__exit__(type, value, traceback)
returns False, the exception will be re-thrown, and the statement logic other than with will handle the exception, which is also a common practice; ifIf True is returned, the exception is ignored and the exception is no longer handled.Python's with statement is an effective mechanism to make the code more concise, and at the same time, when an exception occurs, the cleanup work is easier.
class DBManager(object):def __init__(self):passdef __enter__(self):print('__enter__')return selfdef __exit__(self, exc_type, exc_val, exc_tb):print('__exit__')return Truedef getInstance():return DBManager()with getInstance() as dbManagerIns:print('with demo')
with must be followed by a context manager. If as is used, the return value of the context manager's __enter__()
method is assigned to target, which can be a single variable, or byA tuple enclosed by "()" (cannot be a list of variables separated only by ",", must add "()")
The result of running the code is as follows:
'''__enter__with demo__exit__'''
Result analysis: When we use with, the __enter__
method is called, and the return value is assigned to the variable after as, and __exit__ is automatically executed when exiting withcode>Method
'''Problems encountered during study and no one answered?Xiaobian created a Python learning exchange group: 711312441Looking for like-minded friends to help each other, there are also good video learning tutorials and PDF e-books in the group!'''class With_work(object):def __enter__(self):"""Called when entering the with statement"""print('enter called')return "xxt"def __exit__(self, exc_type, exc_val, exc_tb):"""Called by with when leaving with"""print('exit called')with With_work() as f:print(f)print('hello with')
'''enter calledxxthello withexit called'''
Customize context managers to manage resources in the software system, such as database connections, access control of shared resources, etc.