[Python-Dev] with-statement heads-up
Guido van Rossum
guido at python.org
Tue Feb 28 23:36:26 CET 2006
On 2/28/06, Phillip J. Eby <pje at telecommunity.com> wrote:
> Notice that these semantics break some of the PEP examples. For
> example, the 'locked' and 'nested' classes now suppress exceptions,
> and it took a non-trivial study of their code to determine
> this. This seems to suggest that making suppression the default
> behavior is a bad idea.
I presume you're referring to example 4 (locked as a class), not
example 1 (locked as a generator). I'll fix this, and rewrite nested()
as a generator (just like what I checked in :-).
> I was originally on the side of allowing suppression, but I wanted it
> to be done by explicitly returning some non-None value, so that
> suppression would not be the default, implicit behavior. I think I'd
> prefer not to be able to suppress the errors, than to have errors
> pass silently unless explicitly re-raised! I don't see a problem
> with having e.g. __exit__ have to return a flag to suppress the
> exception; it wouldn't need to change how @contextmanager functions
> are written. (Implicit suppression is only a problem for people
> writing __exit__ methods, in other words; all your reasoning about
> @contextmanager generators is valid, IMO.)
Thanks for the validation of the idea -- I ran into this when writing
unittests for @contextmanager...
I think that providing sufficient *correct* examples will avoid most
of the problems. People will clone existing examples (I know *I* did
when adding context managers to various modules :-).
Changing the API to let __exit__() return something true to suppress
the exception seems somewhat clumsy. Re-raising the exception is
analogous to the throw() method in PEP 342.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list