Fluent Python chapter 15th context Manager and Else block Learning records

Source: Internet
Author: User
Tags function definition

With statement and context Manager
else clauses for for, while, and try statements

The WITH statement sets a temporary context, gives control to the context Manager object, and is responsible for cleaning up and down
Text Doing so avoids errors and reduces boilerplate code, so the API is more secure and easier to use. In addition to Automatic
There are many uses for the With block in addition to closing the file

The ELSE clause can be used not only in an if statement,
can also be used in the for, while, and try statements

For
The Else block is run only when the For loop finishes running (that is, the for loop is not aborted by the break statement).
While
Only when the while loop exits because the condition is false (that is, the while loop is not aborted by the break statement)
Before the else block is run.
Try
The Else block is run only if no exception is thrown in the try block. Official documents
(https://docs.python.org/3/reference/compound_stmts.html) also states: "The exception thrown by the ELSE clause
is not handled by the preceding except clause. ”
In all cases, if the exception or return, break, or continue statement causes control to jump to the compound
The ELSE clause is skipped in addition to the main block of the

Context Manager and with blocks
The purpose of the context Manager object is to manage the WITH statement, just as the iterator exists to manage the for statement
The same.
The WITH statement is designed to simplify the try/finally pattern. This mode is used to ensure that a piece of code is executed after it finishes
An operation, even if that code is aborted due to an exception, return statement, or Sys.exit () call
The specified action. The code in the finally clause is typically used to release important resources, or to restore temporary changes to the
State.
The context Manager protocol contains two methods of __enter__ and __exit__. When the With statement starts running, it is
The __enter__ method is called on the context manager object. When the WITH statement finishes running, the context Manager
The __exit__ method is called on the elephant to play the role of the finally clause.

When the interpreter calls the __enter__ method, no arguments are passed in addition to the implicit self. To
The three parameters of the __exit__ method are listed below.
Exc_type

The exception class (for example, Zerodivisionerror).
Exc_value
The exception instance. Sometimes arguments are passed to the exception construction method, such as error messages, which can be used
Exc_value.args get.
Traceback
Traceback Object

。 Apart from
The Redirect_stdout function mentioned earlier, there are classes and other functions in the Contextlib module, using the
More extensive.
Closing
If the object provides a close () method, but does not implement the __ENTER__/__EXIT__ protocol, you can
Use this function to build the context manager.
Suppress
Constructs a context manager that temporarily ignores the specified exception.
@contextmanager
This decorator turns a simple generator function into a context manager, so you don't have to create a class to implement the manager
Agreement.
Contextdecorator
This is a base class that defines a class-based context manager. This context manager can also be used for decorating letters
Run the entire function in the managed context.
Exitstack
This context manager can enter multiple context managers. At the end of the With block, the exitstack follows the backward
The __exit__ method of each context manager in the stack is called in the first out order. If you don't know the With block in advance,
The number of context managers that can be used in this class. For example, opening all of the files in any file list at the same time
Thing

@contextmanager adorners Reduce the amount of boilerplate code that creates a context manager, because you do not have to write an end
Class, define the __enter__ and __exit__ methods, and simply implement a generator with a yield statement,
Generates a value that you want the __enter__ method to return.
In a builder that uses @contextmanager decoration, the yield statement is divided into two of the defined body of the function.
Section: All the code in front of the yield statement is at the start of the With block (that is, the interpreter calls the __enter__ method
Execution, the code following the yield statement executes when the With block ends (that is, when the __exit__ method is called)

In fact, the Contextlib.contextmanager decorator will wrap the function to implement __ENTER__ and
Of the __exit__ method

The __enter__ method of this class has the following effect.
(1) Call the generator function to save the generator object (this is called Gen).
(2) Call Next (Gen) and execute to the location where the yield keyword is located.
(3) Returns the value of the next (gen) output to bind the output value to the target variable in the With/as statement.
The __exit__ method does several things when the With block terminates.
(1) Check whether the exception is passed to Exc_type; if there is, call Gen.throw (exception) in the generated
The line in the body that contains the yield keyword throws an exception.
(2) Otherwise, call next (gen) to continue executing the code after the yield statement in the body of the generator function definition.

When using @contextmanager adorner, place the yield statement in the try/finally statement
(or put in the With statement), which is unavoidable because we never know the context Manager
What the user will do in the With block.

Fluent Python chapter 15th context Manager and Else block Learning records

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.