[DB-SIG] Standardized "with" block behavior?

M.-A. Lemburg mal at egenix.com
Mon Sep 25 10:27:16 CEST 2006


Carsten Haese wrote:
> Hiya folks,
> 
> Now that Python 2.5 is offically out and has introduced "with" blocks
> (http://docs.python.org/whatsnew/pep-343.html), I'm wondering if we
> (i.e. the module authors) should standardize how DB-API compliant
> modules leverage this functionality.
> 
> One obvious possibility is that connection and cursor objects could
> return themselves in __enter__ and close themselves on __exit__. This
> would allow the user to write something like this:
> 
> with module.connect(...) as conn:
>    with conn.cursor() as cur:
>       # ...
> 
> which is much easier to read than the equivalent:
> 
> conn = module.connect(...)
> try:
>    cur = conn.cursor()
>    try:
>       # ...
>    finally:
>       cur.close()
> finally:
>    conn.close()
> 
> I've already implemented this behavior for InformixDB in CVS, but if
> people have better ideas, I'm definitely open to suggestions.

Sounds reasonable, though strictly speaking, the with-container
is not necessary, since cursors and connections will close themselves
when garbage collected, ie. as soon as they go out of scope.

In some cases it may not even be desirable to close the cursor or
connection, since this prevents effective debugging (the traceback
passed to outer scopes will contain a reference to the cursor and
connection, keeping them open).

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Sep 25 2006)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::


More information about the DB-SIG mailing list