python and introduced new exception-related statement--the withand its optional as clause this statement is designed to work with context manager objectswhich support new method-based protocolsimilar in spirit to the way that iteration tools work with methods of the iteration protocol this feature is also available as an option in but must be enabled there with an import of this formfrom __future__ import with_statement the with statement is also similar to "usingstatement in the clanguage although somewhat optional and advanced tools-oriented topic (and once candidate for the next part of the book)context managers are lightweight and useful enough to group with the rest of the exception toolset here in shortthe with/as statement is designed to be an alternative to common tryfinally usage idiomlike that statementwith is in large part intended for specifying termination-time or "cleanupactivities that must run regardless of whether an exception occurs during processing step unlike try/finallythe with statement is based upon an object protocol for specifying actions to be run around block of code this makes with less generalqualifies it as redundant in termination rolesand requires coding classes for objects that do not support its protocol on the other handwith also handles entry actionscan reduce code sizeand allows code contexts to be managed with full oop python enhances some built-in tools with context managerssuch as files that automatically close themselves and thread locks that automatically lock and unlockbut programmers can code context managers of their own with classestoo let' take brief look at the statement and its implicit protocol basic usage the basic format of the with statement looks like thiswith an optional part in square brackets herewith expression [as variable]with-block the expression here is assumed to return an object that supports the context management protocol (more on this protocol in momentthis object may also return value that will be assigned to the name variable if the optional as clause is present note that the variable is not necessarily assigned the result of the expressionthe result of the expression is the object that supports the context protocoland the variable may be assigned something else intended to be used inside the statement the object returned by the expression may then run startup code before the with-block is startedas well as termination code after the block is doneregardless of whether the block raised an exception or not exception coding details