variable scope in try ... EXCEPT block.
codewizard at gmail.com
codewizard at gmail.com
Fri Jul 13 00:44:07 EDT 2018
On Thursday, July 12, 2018 at 7:16:48 PM UTC-4, Chris Angelico wrote:
> On Fri, Jul 13, 2018 at 8:10 AM Igor 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
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".
Regards,
Igor.
More information about the Python-list
mailing list