[DB-SIG] Context manager support for cursors

Daniel Lenski dlenski at gmail.com
Wed Jul 25 23:30:31 EDT 2018

On Tue, Jul 24, 2018 at 12:37 AM, Federico Di Gregorio <fog at dndg.it> wrote:
> On 06/21/2018 01:31 AM, Gerald Venzl wrote:
>> Hi all,
>> I was wondering whether there has been any particular reason that the
>> specification of the Cursor object doesn’t implement a context manager to
>> enable for example the “with” statement?
>> Being able to use the “with” statement for database cursors, just like
>> other external resources like files, etc., I think makes a lot of sense:
>> with conn.cursor()as c:
>>      c.execute("SELECT 'test' from dual")
>>      result = c.fetchall()
>>      print(result)
> It does (make sense). The explanation is that context managers did not exist
> when the PEP was written. An update is long overdue, IMHO.

Indeed. contextlib.closing
can be used to emulate the same behavior, but it really ought to be
part of the DBAPI specification.

Python Database API Specification v3.0, anyone…? :-P


More information about the DB-SIG mailing list