[DB-SIG] Use of context managers with DB API 2

Peter Eisentraut peter at eisentraut.org
Fri Nov 2 19:11:36 CET 2012


On 11/2/12 5:53 AM, Christoph Zwerschke wrote:
> What I find a bit ugly about this approach is that now the context
> managers of connections and cursors behave differently, and that code
> written using these context managers is not self-explanatory. If
> connections and cursors would just have closing context managers, and
> connections had an extra "transaction" member that is a context manager
> for handling the transaction, the code would be more readable and
> explicit which is better than implicit:
> 
>     with dbapi2.connect(...) as con:
>         with con.transaction:
>             with con.cursor() as cur:
>                 cur.execute("insert into debit(amount) values (-100)")
>                 cur.execute("insert into credit(amount) values (100)")
>         with con.transaction:
>             with con.cursor() as cur:
>                 cur.execute("insert into debit(amount) values (-200)")
>                 cur.execute("insert into credit(amount) values (200)")

I agree that that makes a lot more sense.


More information about the DB-SIG mailing list