I came across the Python with
statement for the first time today. I\'ve been using Python lightly for several months and didn\'t even know of its existence! G
Another example for out-of-the-box support, and one that might be a bit baffling at first when you are used to the way built-in open()
behaves, are connection
objects of popular database modules such as:
The connection
objects are context managers and as such can be used out-of-the-box in a with-statement
, however when using the above note that:
When the
with-block
is finished, either with an exception or without, the connection is not closed. In case thewith-block
finishes with an exception, the transaction is rolled back, otherwise the transaction is commited.
This means that the programmer has to take care to close the connection themselves, but allows to acquire a connection, and use it in multiple with-statements
, as shown in the psycopg2 docs:
conn = psycopg2.connect(DSN)
with conn:
with conn.cursor() as curs:
curs.execute(SQL1)
with conn:
with conn.cursor() as curs:
curs.execute(SQL2)
conn.close()
In the example above, you'll note that the cursor
objects of psycopg2
also are context managers. From the relevant documentation on the behavior:
When a
cursor
exits thewith-block
it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected.