[Python-Dev] Explicitly declaring expected exceptions for a block

Nick Coghlan ncoghlan at gmail.com
Tue Jun 21 16:51:07 CEST 2005


Paul Du Bois wrote:
> If I understand PEP 343 correctly, it allows for easy implementation
> of part of your request. It doesn't implement the else: clause, but
> you don't give a use case for it either.
> 
> class ignored_exceptions(object):
>    def __init__(self, *exceptions):
>        self.exceptions = exceptions
>    def __enter__(self):
>        return None
>    def __exit__(self, type, value, traceback):
>        try:
>            raise type, value, traceback
>        except self.exceptions:
>            pass
> 
> with ignored_exceptions(SomeError):
>    do stuff
> 
> I don't see the use, but it's possible.

It was possible in PEP 340 and in early drafts of PEP 346, but it 
isn't possible in PEP 343.

In PEP 343, the statement template *cannot* suppress exceptions - it 
can react to them, and it can turn them into different exceptions, but 
that's all.

And yes, this is deliberate - the control flow is too murky otherwise:

   with some_template():
       raise TypeError
   print "Hi!"

Does that code print "Hi!" or not? Under PEP 343, you know it doesn't, 
because the TypeError isn't trapped. If templates could actually 
suppress exceptions, you'd have no idea what the code does without 
looking up the definition of 'some_template' - this is a bad thing, 
which is why PEP 343 defines the semantics the way it does.

However, I'm with Michael - every time I've needed something like 
this, I have had non-trivial code in either the 'except' or the 'else' 
blocks of the try statement.

Regards,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list