[DB-SIG] DB API extension suggestion

M.-A. Lemburg mal at egenix.com
Thu Jun 21 19:40:54 CEST 2007


On 2007-06-21 18:41, Anthony Tuininga wrote:
> I have been recently playing with context managers and the new "with"
> statement added in Python 2.5. I would like to suggest the addition of
> the following methods  to connections:
> 
> def __enter__(self):
>     return self
> 
> def __exit__(self, excType, excValue, excTraceback):
>     if excType is None and excValue is None and excTraceback is None:
>         self.commit()
>     else:
>         self.rollback()

Do you really think this is such a good idea ?

You normally want to catch the exception and then act on
it rather than just rollback the transaction and these
actions usually depend on what the application is doing.

Likewise, you typically want to be explicit about a commit
on a connection.

OTOH, a programmer could simply choose not to use "with" to
implement a different coding strategy.

> This allows the following code:
> 
> from __future__ import with_statement
> 
> connection = .....
> with connection:
>     cursor = connection.cursor()
>     cursor.execute("update SomeTable set SomeColumn = "SomeValue")
>     cursor.execute("delete from SomeOtherTable where SomeOtherColumn = 5)
>
> rather than
> 
> try:
>     cursor = connection.cursor()
>     cursor.execute("update SomeTable set SomeColumn = "SomeValue")
>     cursor.execute("delete from SomeOtherTable where SomeOtherColumn = 5)
>     connection.commit()
> except:
>     connection.rollback()
>
> I've implemented this in cx_Oracle and it appears to work quite
> nicely. Thoughts?

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jun 21 2007)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________
2007-07-09: EuroPython 2007, Vilnius, Lithuania            17 days to go

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


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611


More information about the DB-SIG mailing list