On 29 April 2018 at 13:14, Chris Angelico <ros...@gmail.com> wrote: > There's been a lot of talk about sublocal scopes, within and without > the context of PEP 572. I'd like to propose what I believe is the > simplest form of sublocal scopes, and use it to simplify one specific > special case in Python. > > There are no syntactic changes, and only a very slight semantic change. > > def f(): > e = 2.71828 > try: > 1/0 > except Exception as e: > print(e) > print(e) > f() > > The current behaviour of the 'except... as' statement is as follows: > > 1) Bind the caught exception to the name 'e', replacing 2.71828 > 2) Execute the suite (printing "Division by zero") > 3) Set e to None > 4) Unbind e > > Consequently, the final print call raises UnboundLocalError. I propose > to change the semantics as follows: > > 1) Bind the caught exception to a sublocal 'e' > 2) Execute the suite, with the reference to 'e' seeing the sublocal > 3) Set the sublocal e to None > 4) Unbind the sublocal e > > At the unindent, the sublocal name will vanish, and the original 'e' > will reappear. Thus the final print will display 2.71828, just as it > would if no exception had been raised. >
The challenge with doing this implicitly is that there's no indication whatsoever that the two "e"'s are different, especially given the longstanding precedent that the try/except level one will overwrite any existing reference in the local namespace. By contrast, if the sublocal marker could be put on the *name itself*, then: 1. Sublocal names are kept clearly distinct from ordinary names 2. Appropriate sublocal semantics can be defined for any name binding operation, not just exception handlers 3. When looking up a sublocal for code compiled in exec or eval mode, missing names can be identified and reported at compile time (just as they can be for nonlocal declarations) (Such a check likely wouldn't be possible for code compiled in "single" mode, although working out a suitable relationship between sublocal scoping and the interactive prompt is likely to prove tricky no matter what) Cheers, Nick. -- Nick Coghlan | ncogh...@gmail.com | Brisbane, Australia
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/