8.python Context Management Protocol

Source: Internet
Author: User

What are the benefits of using context management protocols?

    1. The purpose of using the WITH statement is to put a block of code in with, and with the end, the cleanup work is done automatically without manual Intervention.

    2. In a programming environment where you need to manage some resources such as files, network connections, and locks, You can customize the mechanism for automatically releasing resources in __exit__, which is useful if you don't have to relate to this Issue.


The previously mentioned with Code block, which is Python's context management operations, such as open a file through python, can be implemented by using the with code block with open, in this way open the file, do the corresponding operation, do not need us to manually go to the close file, The file will be automatically Closed.

Like what:

With open (' a.txt ') as F:

' Code block '

# The above example is a context management protocol, the with statement, in order for an object to be compatible with the with statement, the __enter__ and __exit__ methods must be declared in the class of the Object.

The management of this context is achieved through two built-in methods, __enter__ and __exit__ in the class.


The following are examples of usage of __enter__ and __exit__:

Class Test:

def __init__ (self,name):

Self.name = Name

def __enter__ (self):

#print "as soon as the WITH statement is present, the __enter__ method of this object is triggered, __enter__ The return value of this method is assigned to the variable declared after"

Print "i am the __enter__ method, with the appearance will execute me ~"

def __exit__ (self, exc_type, exc_val, exc_tb):

Print "i am The __exit__ method, __enter__ execution will execute me"

With Test (123) as T1:

Print "aaaa"


Let's take a look at the Output:

I am the __enter__ method, with the appearance will execute me ~

Aaaa

I am the __exit__ method, __enter__ execution will execute my


The three parameters in #__exit__ () represent exception types, outliers, and Trace information, and the code block in the WITH statement has an exception, and the code after it cannot be executed.

# incoming __exit__ method of exc_type,exc_val,exc_tb, respectively (exception class, exception value, tracking Information) These three parameters only if the __enter__ method or with the code block under the exception, these three parameters will have a value, Otherwise it is three NONE.

The three parameters in #__exit__ () represent the exception type, outliers and traceability information, and the code block in the WITH statement has an exception, then the with code cannot execute and the __exit__ method is executed directly.


About exception handling for context Management:

Class Open:

def __init__ (self,name):

Self.name=name

def __enter__ (self):

Print (' A With statement appears, the Object's __enter__ is triggered, The return value is assigned to the variable ' as declared ')

def __exit__ (self, exc_type, exc_val, exc_tb):

Print (execute me when the code block is finished Executing)

Print (exc_type)

Print (exc_val)

Print (exc_tb)

With Open (' a.txt ') as F:

Print (' =====> execute code block ')

Raise Attributeerror (' * * * * fire, Fire AH * * *)

Print (' 0 ' *100) #-------------------------------> will not execute

As can be seen from the above example, when the execution of the code block with the exception, Python will directly begin to execute the Object's __exit__ method, when the __exit__ within the execution of the method, the entire program is Terminated.


so, How do you deal with exceptions in the with Code block?

Take a look at the following example!!


Class Open:

def __init__ (self,name):

Self.name=name

def __enter__ (self):

Print (' A With statement appears, the Object's __enter__ is triggered, The return value is assigned to the variable ' as declared ')

def __exit__ (self, exc_type, exc_val, exc_tb):

Print (execute me when the code block is finished Executing)

Print (exc_type)

Print (exc_val)

Print (exc_tb)

Return True # Note here!!!!

With Open (' a.txt ') as F:

Print (' =====> execute code block ')

Raise Attributeerror (' * * * * fire, Fire AH * * *)

Print (' 0 ' *100) #-------------------------------> will execute



When the __exit__ method returns a value of true, as if nothing happened, the WITH statement executes normally, and the exception in the with code block is masked out!!


finally, for the context management of python, make a summary:

    1. In the absence of any exception, the contents of the entire code block will trigger the Object's __exit__ method when it finishes running, with none of its three parameters.

    2. When there is an exception, the __exit__ is triggered directly from the abnormal Position.

      2.1 When you manually modify the return value of the __exit__ method to a True,with statement, the exception is Masked.

      2.2 When the return value of __exit__ is not true, an exception is thrown in the with code BLOCK.

      2.3 When __exit__ this method once run, it means that the entire with statement is Executed.


This article is from the "rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1918647

8.python Context Management Protocol

Related Article

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.