tags:

views:

103

answers:

2

Hi , I am trying to understand the with statement in python.Everywhere I look it talks of opening and closing a file, and is meant to replace the try , finally block. Could someone post some other examples too.I am just trying out flask and there are with statements galore in it.Definitely request someone to provide some clarity on it

+5  A: 

There's a very nice explanation here. Basically, the with statement calls two special methods on the associated object. The __enter__ and __exit__ methods. The enter method returns the variable associated with the "with" statement. While the __exit__ method is called after the statement executes to handle any cleanup (such as closing a file pointer).

GWW
I'm with the OP. The link you gave demonstrates the "opening and closing a file" example that Alice described, but it doesn't actually show *why* it's better than "data = open("x.txt").read()". It seems like "with" is something I should be considering, but darned if I can tell what it's actually good for.
Just Some Guy
The key reason to use it to avoid having to remember to or deal with any clean up after you are done with something. The with block does that for you. So instead of fp = open() ... fp.close(). You just use a with block.
GWW
But what is the big deal here. A try finally block is much clearer ,cleaner and as said:explicit is better than implicit! :-)
Alice