Python With/as Context Managers

Source: Internet
Author: User

This statement was designed to work with the context manager objects, which support a new method-based protocol, similar in SPI RIT to the the-the-iteration tools work with methods of the iteration protocol.

Basic Usage

The basic format of the WITH statement looks as this, with a optional part on square brackets here:

With Express [as Varial]:with-block

The expression is assumed to return a object that supports the context management Porotocol. This object could also return value that would be assigned to the name variable if the optional as clause is present.

Note that the variable are not necessarily assigned the result of the expression. The result of the expression is the object that supports the context protocol, and the variable could be assigned something else intended to be used inside the statement. The object returned by the expression could then run startup code before the With-block are started, as well as termination C Ode after the block was done, regardless of whether the block raise a exception or not.

A built-in Python object have been augmented to support the context management protocol, and so can be used with the with S Tatement.

>>> with open (r "G:\test.txt") as File:for line in File:print (line)
The context Management Protocol

To implement context management, classes use special methods that fall into the operator overloading category to tap into The WITH statement. This interface expected of objects used in with statement are somewhat complex, and most programmers only need to know how To use existing context manager.

Here's how the WITH statement works:

    1. The expression is valuated, resulting in an object known as a context manager that must has __enter__ and __exit__ method .
    2. The context manager ' s __enter__ method is called. The value it return is assigned to the variable in the AS clause if present, or simply discarded otherwise.
    3. The code in the nested with a block is executed.
    4. IF The block raises an exception, the __exit__ (type, value, Traceback) method was called with the exception in the Python m Anuals and later. If the method returns a false value, the exception is raised. Otherwise, the exception is terminated. The exception should normally be reraised so it's propagated outside the With statement.
    5. If the With block does isn't raise an exception, the __exit__ method was still called, but its type, value and Traceback Argu Ments is passed in as None.

An example of the context management in action:

>>> class TraceBlock (object):d EF __enter__ (self):p rint ("Call __enter__ function") Return Selfdef __exit__ ( Self, exception_type, Exception_value, Exception_trace):p rint ("Call __exit__ function") Print ("Exception info:type:%s value:%s "% (Exception_type, Exception_value)) def action (self, value):p rint (" Call action method ") print (value) >> > with TraceBlock () as I:print ("Start") i.action ("Exit normally") print ("End"), call __enter__ Functionstartcall action Methodexit normallyendcall __exit__ functionexception info:type:None value:none>>> >>> with TraceBlock () as I:print ("Start") i.action ("Raise Exception") Pritn ("End") #not call the Blockcall __enter__ Functionstartcall action methodraise exceptioncall __exit__ functionexception info:type:<type ' exceptions.  Nameerror ' > value:name ' pritn ' isn't definedtraceback (most recent call last): File "<pyshell#684>", line 4, in <module> pritn ("End") #not call the Blocknameerror:name ' pritn ' are not DEfined>>>  

Python With/as Context Managers

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.