Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the 'with' statement do in python? [duplicate]

I am new to Python. In one tutorial of connecting to mysql and fetching data, I saw the with statement. I read about it and it was something related to try-finally block. But I couldn't find a simpler explanation that I could understand.

like image 805
exAres Avatar asked Dec 07 '22 05:12

exAres


1 Answers

with statements open a resource and guarantee that the resource will be closed when the with block completes, regardless of how the block completes. Consider a file:

with open('/etc/passwd', 'r') as f:
    print f.readlines()

print "file is now closed!"

The file is guaranteed to be closed at the end of the block -- even if you have a return, even if you raise an exception.

In order for with to make this guarantee, the expression (open() in the example) must be a context manager. The good news is that many python expressions are context managers, but not all.

According to a tutorial I found, MySQLdb.connect() is, in fact, a context manager.

This code:

conn = MySQLdb.connect(...)
with conn:
    cur = conn.cursor()
    cur.do_this()
    cur.do_that()

will commit or rollback the sequence of commands as a single transaction. This means that you don't have to worry so much about exceptions or other unusual code paths -- the transaction will be dealt with no matter how you leave the code block.

like image 129
Robᵩ Avatar answered Dec 08 '22 20:12

Robᵩ