with statement in Python

with block in Python

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I'll discuss the statement as it will commonly be used. In the next section, I'll examine the implementation details and show how to write objects for use with this statement.

EXPLANATION

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods.

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. (Note carefully that variable is not assigned the result of expression.)

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.
SAMPLE PROGRAM
"""File Handling"""
file = open('file_path''w')
file.write('Hello World !')
file.close()

file = open('file_path''w')
try:
file.write('Hello World')
finally:
file.close()

"""with block use"""
with open('file_path''w'as file:
file.write('Hello World !')

Writing Context Manager

A high-level explanation of the context management protocol is:
The expression is evaluated and should result in an object called a ``context manager''. The context manager must have __enter__() and __exit__() methods.
The context manager's __enter__() method is called. The value returned is assigned to VAR. If no 'as VAR' clause is present, the value is simply discarded.
The code in BLOCK is executed.
If BLOCK raises an exception, the __exit__(type, value, traceback) is called with the exception details, the same values returned by sys.exc_info(). The method's return value controls whether the exception is re-raised: any false value re-raises the exception, and True will result in suppressing it. You'll only rarely want to suppress the exception, because if you do the author of the code containing the 'with' statement will never realize anything went wrong.
If BLOCK didn't raise an exception, the __exit__() method is still called, but type, value, and traceback are all none.

The Contextlib Module


The contextlib module provides some functions and a decorator that are useful for writing objects for use with the 'with' statement.
The decorator is called contextmanager, and lets you write a single generator function instead of defining a new class. The generator should yield exactly one value. The code up to the yield will be executed as the __enter__() method, and the value yielded will be the method's return value that will get bound to the variable in the 'with' statement's as clause, if any. The code after the yield will be executed in the __exit__() method. Any exception raised in the block will be raised by the yield statement.


---Thanks For Reading ---
Share:

Post a Comment

Copyright © DevTipsNTricks. Designed by OddThemes