Python 3 removes name binding from outer scope

Stefan Behnel stefan_ml at behnel.de
Tue Jul 25 03:01:42 EDT 2017


Ben Finney schrieb am 25.07.2017 um 08:34:
> Ethan Furman writes:
> 
>> Something like:
>>
>>     try:
>>         ....
>>     except ZeroDivisionError as dead_exc:
>>         exc = dead_exc
>>         ....
>>     ....
>>     print(text_template.format(exc=exc)
> 
> That strikes me as busy-work; the name in the ‘except’ clause already
> *has* the object, and is a servicable name already.
> 
> Having to make another name for the same object, merely to avoid some
> surprising behaviour, is IMO un-Pythonic.

It's an extremely rare use case and keeping the exception alive after
handling has clear drawbacks in terms of resource usage (exception
information, tracebacks, frames, local variables, chained exceptions, ...)

This tradeoff was the reason why this was changed in Py3k at the time,
together with the introduction of exception chaining (and some other
cleanups in that corner).

Basically, it's better to save resources by default and let users
explicitly keep them alive if they still need them, than to implicitly hold
on to them in a deep corner of CPython (sys.exc_info()) and let users
figure out how to release them explicitly if they find out that they hurt
and then additionally manage to debug where they are stored. Py2.x did the
latter, and guess how many users knew about it?

Stefan




More information about the Python-list mailing list