variable scope in try ... EXCEPT block.

Chris Angelico rosuav at gmail.com
Thu Jul 12 19:16:34 EDT 2018


On Fri, Jul 13, 2018 at 8:10 AM,  <codewizard at gmail.com> wrote:
> On Thursday, July 12, 2018 at 5:45:52 AM UTC-4, Ben Bacarisse wrote:
>> aleiphoenix writes:
>>
>> [snip]
>>
>>   When an exception has been assigned using as target, it is cleared at
>>   the end of the except clause. This is as if
>>
>>   except E as N:
>>       foo
>>
>>   was translated to
>>
>>   except E as N:
>>       try:
>>           foo
>>       finally:
>>           del N
>
> Is there a downside of implementing
> it similarly to this (untested):
>
>   # generate a unique name for __except_N
>   except E as __except_N:
>     if 'N' in locals() or N in globals():
>       __original_N = N
>
>     N = __except_N
>     try:
>       foo()
>     finally:
>       del __except_N
>
>       if '__original_N' in locals():
>         N = __original_N
>         del __original_N
>       else:
>         del N

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


More information about the Python-list mailing list