[Python-ideas] Block-Scoped Exception Handlers

Nick Coghlan ncoghlan at gmail.com
Wed May 4 22:29:51 EDT 2016


On 5 May 2016 at 12:17, Michael Selik <michael.selik at gmail.com> wrote:
> On Wed, May 4, 2016, 8:42 PM Nick Coghlan <ncoghlan at gmail.com> wrote:
>>
>> @contextmanager
>> def chain_errors(exc_to_raise):
>>     try:
>>         yield
>>     except Exception as e:
>>         raise exc_to_raise from e
>
>
> Unfortunately, Kyle is using Python 2.7 still, so ``raise from`` won't help
> him. The exception context/cause is probably my favorite Python 3 feature.
> Or at least in my top 5.

For feature proposals on python-ideas it's the current capabilities on
3.x that matter and there, between exception chaining,
contextlib.contextmanager, and contextlib.ExitStack, there are already
some enormously powerful tools for exception stack manipulation
without extensive code duplication.

Python 2.7 doesn't have the implicit exception chaining, but it does
have the other features (including ExitStack, by way of contextlib2).
While the standard traceback display functions wouldn't show it, even
explicit exception chaining can be emulated on Python 2.x (since
that's mainly just a matter of setting the __cause__ attribute
appropriately and using traceback2 to attach and display gc-friendly
__traceback__ attributes )

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list