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:
- The expression is valuated, resulting in an object known as a context manager that must has __enter__ and __exit__ method .
- 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.
- The code in the nested with a block is executed.
- 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.
- 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