The WITH statement is useful for accessing resources, ensuring that the necessary "cleanup" operations are performed regardless of whether an exception occurs during use, freeing up resources such as automatic shutdown after file use, automatic acquisition and release of locks in threads, and so on.
Example:
With open (R'somefilename') as Somefile: Somefile: Print line # ... more code
Custom apps:
classDummyresource:def __init__(self, Tag): Self.tag=TagPrint 'Resource [%s]'%Tagdef __enter__(self):Print '[Enter%s]: Allocate resource.'%Self.tagreturnSelf#can return different objects def __exit__(self, exc_type, Exc_value, EXC_TB):Print '[Exit%s]: free resource.'%Self.tagifExc_tb isNone:Print '[Exit%s]: Exited without exception.'%Self.tagElse: Print '[Exit%s]: Exited with exception raised.'%Self.tagreturnFalse#can be omitted, the default of None is also considered false
Python with statement