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).
Syntax
with expression [as variable]:
with-block
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

try:
file = open("myFile.txt", "r")
print(file.read())
except:
print("An error has occurred!")
finally:
file.close()
The following example using the Python "with statement" .
example
with open("myFile.txt", "r") as file:
print(file.read())
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

example
lock = threading.Lock()
with lock:
thread1.start()
thread2.start()
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.
Related Topics