Python WITH statements


Before we start any essential work it’s obvious we need to initialize something and cleanup in the end, else you mom will definitely scold you J

In Programming say for example opening file or using database say for example
You need to open file before you write and you need to close file after your job done.
How can we achieve this in python efficiently? And real pythonic way?

Here come WITH statement added in python 2.5 release

How to use it?
opening file and closing on its own


with open("log.txt") as f:
    data = f.read()
    play with data
    do some thing

In threading acquiring lock and releasing automatically

 lock = threading.Lock()
 with lock:
     Play with critical section
     Access shared objects 
 
How with works?

Any class you write, to adopt with WITH you need to write __enter__() and __exit__() methods.

All the code to be executed when interpreter hits with code block to be written inside __enter__
The code which needed to be executed before leaving with block to be written in __exit__
Tats all you need to do

Look at the example


class Example:

  def __enter__(self):
    Initialize connection
    Or open file          

  def __exit__(self):
    Close connection
    Or close files

    with Example() as thing:   # __enter__() will be called after creation of object
      Do something using thing
      Do more
                               # _exit__() will be called before leaving block
  lock = threading.Lock()
  with lock:
    Play with critical section
    Access shared objects