InterviewSolution
| 1. |
Explain how useful Python’s ‘with’ statement is. |
|
Answer» The intention of ‘with’ statement in Python is to make the code cleaner and much more readable. It simplifies the management of common resources like FILE streams. The ‘with’ statement establishes a context manager object that defines the runtime context. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are NORMALLY invoked using the ‘with’ statement. Here is a typical use of with statement. Normally a file object is declared with built-in open() function. After performing file read/write operations the file object must be relieved from memory by its close() method failing which the disk file/stream underneath the object may be corrupted. >>> F=open('file.txt','w') >>> f.write('Hello') >>> f.close()Use of ‘with’ statement sets up a context for the FOLLOWING block of statements. As the block finishes, the context object also automatically goes out of scope. It need not be explicitly destroyed. >>> with open('file.txt','w') as f: f.write('Hello')Note that the object f is no longer ALIVE after the block and you don’t have to call close() method as earlier. Hence, the code becomes clean and easy to read. The file object acts as a context manager object by default. To define a custom context manager, the class must have __enter__() and __exit__() methods. class Mycontext: def __init__(self): print ('object initialized') def __enter__(self): print ('context manager entered') def __exit__(self, type, value, traceback): print ('context manager exited') with Mycontext() as x: print ('context manager example')Output: object initialized context manager entered context manager example context manager exited |
|