[Python-ideas] Sublocal scoping at its simplest
rosuav at gmail.com
Sat Apr 28 23:14:54 EDT 2018
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.
e = 2.71828
except Exception as e:
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 above definitions would become language-level specifications. For
CPython specifically, my proposed implementation would be for the name
'e' to be renamed inside the block, creating a separate slot with the
With no debates about whether "expr as name" or "name := expr" or
"local(name=expr)" is better, hopefully we can figure out whether
sublocal scopes are themselves a useful feature :)
More information about the Python-ideas