← Back to team overview

launchpad-dev team mailing list archive

Re: The with statement

 

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Barry Warsaw wrote:

> I'm not sure the with-statement was designed for transactions, but one good
> reason why it shouldn't be used for transactions is because (IME) proper
> handling doesn't fit into pure try/finally:
> 
>     txn = transaction.begin()
>     try:
>         modify_the_database()
>     except:
>         # Yes, bare except.
>         txn.abort()

I would usually have a raise here.

>     else:
>         # Ah, everything succeeded.
>         txn.commit()
> 
> That's not a good fit for 'with'.  I suppose you can wedge it into the context
> manager protocol, but it wouldn't be the first thing I'd reach for.

Why not?  Don't you just switch between txn.abort() and txn.commit()
according to whether __exit__ is called with an exception?

ISTM that try/finally is just syntactic sugar for try/except+raise/else,
and that context managers handle the latter just fine.

Aaron
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkt0PO0ACgkQ0F+nu1YWqI1IOQCdHbNYi+7Wkzngt0Q7nAHak2g3
FIUAn3Ka/3jWWuWiSRof7/lpuzVKYdLK
=Zsdz
-----END PGP SIGNATURE-----



Follow ups

References