variable scope in try ... EXCEPT block.

Chris Angelico rosuav at gmail.com
Fri Jul 13 00:54:14 EDT 2018


On Fri, Jul 13, 2018 at 2:44 PM,  <codewizard at gmail.com> wrote:
> On Thursday, July 12, 2018 at 7:16:48 PM UTC-4, Chris Angelico wrote:
>> Not sure, but here's a simpler implementation:
>>
>> except Exception as .err.0:
>>     print(.err.0)
>>     .err.0 = None
>>     del .err.0
>>
>> In other words, exactly the same as the current behaviour, except that
>> (sorry, pun intended) inside the block, the name is modified to
>> something that can't actually be used. (The token ".err.0" functions
>> like an actual local name, just one that's syntactically invalid and
>> thus cannot ever conflict.) Once you exit the except block, the
>> previous value will magically reappear, because it didn't go anywhere.
>> Multiple except blocks - nested or separate - would have separate
>> names (".err.1", ".err.2"), so they won't conflict with each other.
>>
>> ChrisA
>
> Simpler is better. The point is that something like this would accomplish both:
>
> 1. Break the reference cycle.
>
> 2. Avoid what is (IMHO) an unexpected behavior of a variable declared prior to try/except disappearing after getting shadowed by "except as".
>

Added bonus: I've already implemented the version I described. So if
you want it, dig around on python-ideas and find where I posted it.

ChrisA


More information about the Python-list mailing list