with statement in Python
The with statement in Python simplifies exception handling by encapsulating common preparation and clean-up tasks in so-called context managers. This allows common try..except..finally usage patterns to be encapsulated for convenient reuse and reduce the amount of code you need to write for handling different kinds of exceptions. The with statement creates resources within a block . You write your code using the resources within the block. When the block exits the resources are cleanly released regardless of the outcome of the code in the block (that is whether the block exits normally or because of an exception).
The with statement has an __enter() and an __exit() function that it calls at the beginning and the end of the statement. The object's __enter__() is called before with-block is executed and therefore can run set-up code. It also may return a value that is bound to the name variable, if given. After execution of the with-block is finished, the object's __exit__() method is called, even if the block raised an exception, and can therefore run clean-up code. It is similar to the "using statement" in .Net Languages.
With Statement Usage
In most cases, the Python with keyword is used when working with unmanaged resources (like file streams). It provides 'syntactic sugar' for try...finally blocks . Following is an example using the try, except, and finally statements for opening and reading a file called "myFile.txt".
The following example using the Python "with statement" .
In the above example, with statement will automatically close the file after the nested block of code. The advantage of using a with statement is that it is ensure to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler . If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in the previous cases, too.
with statement in Threading
Many resources in the Python library that obey the protocol required by the with statement and so can used with it out-of-the-box. Use it whenever you acquire resources in your application that must be explicitly relinquished such as files, network connections, locks and the like.