The context manager is a syntax that Python2.5 begins to support, which is used 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 objects). Its grammatical form is with...as ...
Close File
We will do this: Open the file, read and write, and close the file. Programmers often forget to close files. The context manager can automatically close a file when it is not needed.
Now let's take a look at two procedures:
Copy Code code 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:
Copy Code code as follows:
# with Context Manager
With open ("New.txt", "W") as F:
Print (f.closed)
F.write ("Hello world!")
Print (f.closed)
The two procedures actually perform the same operation. Our second program uses the context Manager (With...as ...). The context manager has a program block that is subordinate to it. The context Manager automatically closes the file when the subordinate block execution ends (that is, it is no longer indented) (we query the file for closure by f.closed). We are equivalent to using indentation to specify the scope of use of the file object F.
The above context manager is based on the __exit__ () special method of the F object (remember how we used special methods to implement various syntaxes?). Refer to special methods and multiple paradigms). When we use the context Manager syntax, we actually require Python to call the object's __enter__ () method before entering 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 explicitly close the F file.
Custom
Any object that defines the __enter__ () and __exit__ () methods can be used for the context manager. The file object F is a built-in object, so F automatically comes with these two special methods and does not need to be customized.
Below, we customize the object for the context manager, which is the following myvow:
Copy Code code 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:
Copy Code code as follows:
I say:i ' m fine
I say:i ' m fine!
We can see that the Text property of the object has changed (the original Text property is "I ' M fine") as it enters the context and leaves the context.
__ENTER__ () returns an object. The context manager uses this object as the variable referred to as, i.e. myvow. In __enter__ (), we added a prefix for myvow.text ("I say:"). In __exit__ (), we added a suffix ("!") to the Myvow.text.
Note: There are four parameters in __exit__ (). When an exception (exception) is present in the block, the __exit__ () parameter is Exc_type, Exc_value, and Traceback is used to describe the exception. We can do the corresponding processing according to these three parameters. These three parameters are none if the normal operation ends. 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:
Copy Code code 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 tool worth using.