Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python "with" statement used for?

Tags:

python

flask

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.

like image 243
Rasmus Avatar asked Dec 02 '22 04:12

Rasmus


1 Answers

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).

like image 157
GWW Avatar answered Dec 05 '22 03:12

GWW