The context manager is a syntax that Python2.5 begins to support to specify the scope of use of an object. Once you enter or leave the scope of use, special actions are invoked (such as allocating or freeing memory for an object). Its grammatical form is with...as ...
Close File
We will do this: Open the file, read and write, close the file. Programmers often forget to close files. The context Manager can automatically close files when no files are needed.
Let's take a look at two programs:
The code is as follows:
# without context Manager
f = open ("New.txt", "W")
Print (f.closed) # Whether the file is open
F.write ("Hello world!")
F.close ()
Print (f.closed)
And:
The code is as follows:
# with Context Manager
With open ("New.txt", "W") as F:
Print (f.closed)
F.write ("Hello world!")
Print (f.closed)
The two programs actually perform the same operation. Our second program uses the context Manager (With...as ...). The context manager has a program block that belongs to it. The context Manager automatically closes the file (we can query whether the file is closed by f.closed) when the subordinate block execution is finished (that is, no longer indented). It is equivalent to using indentation to specify the scope of use of the file object F.
The context manager above is based on the __exit__ () special method of the F object (remember how we use special methods to implement various syntaxes?). See special methods and multiple paradigms). When we use the syntax of the context manager, we actually ask Python to call the __enter__ () method of the object before it enters the block, and call the __exit__ () method when the block is closed. For file object F, it defines the __enter__ () and __exit__ () methods (which can be seen through Dir (f)). In the __exit__ () method of F, there is a self.close () statement. So when using the context manager, we don't have to close the F file in plaintext.
Custom
Any object that defines the __enter__ () and __exit__ () methods can be used in the context manager. The file object F is a built-in object, so F automatically comes with these two special methods and does not require customization.
Below, we customize the object for the context manager, which is the following myvow:
The code is as follows:
# Customized Object
Class VOW (object):
def __init__ (self, text):
Self.text = text
def __enter__ (self):
Self.text = "I say:" + self.text # Add prefix
Return self # Note:return an object
def __exit__ (Self,exc_type,exc_value,traceback):
Self.text = Self.text + "!" # Add suffix
With VOW ("I ' M Fine") as Myvow:
Print (Myvow.text)
Print (Myvow.text)
The results of our operation are as follows:
The code is as follows:
I say:i ' m fine
I say:i ' m fine!
As we can see, the object's Text property has changed when entering the context and leaving the context (the original Text property is "I ' M fine").
__ENTER__ () returns an object. The context manager uses this object as the variable referred to as, which is myvow. In __enter__ (), we added a prefix for myvow.text ("I say:"). In __exit__ (), we added a suffix ("!") to Myvow.text.
Note: There are four parameters in __exit__ (). When an exception occurs in the block (exception), the parameters of __exit__ () Exc_type, Exc_value, traceback are used to describe the exception. We can do the corresponding processing according to these three parameters. If the operation ends, all three parameters are none. In our program, we do not use this feature.
Summarize:
Through the context Manager, we control the characteristics of objects in different intervals of the program. The context manager (with EXPR as VAR) is roughly equivalent to the following process:
The code is as follows:
# with EXPR as VAR:
VAR = EXPR
VAR = var.__enter__ ()
Try
BLOCK
Finally
Var.__exit__ ()
Because of the convenience of the context manager, it is a worthwhile tool to use.