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
2010-09-28 14:42:44
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
2010-09-28 19:24:13
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
2010-09-28 20:33:17
But what is the big deal here. A try finally block is much clearer ,cleaner and as said:explicit is better than implicit! :-)
Alice
2010-09-29 02:38:11