[Python-ideas] Give nonlocal the same creating power as global

Nick Coghlan ncoghlan at gmail.com
Tue Sep 12 06:54:26 EDT 2017


On 12 September 2017 at 03:32, João Matos <jcrmatos at gmail.com> wrote:
> Hello,
>
> You're correct. The idea is to give nonlocal the same ability, redirect
> subsequent bindings if the variable doesn't exist.

The issue you're facing is that optimised local variables still need
to be defined in the compilation unit where they're locals - we're not
going to make the compiler keep track of all the nonlocal declarations
in nested functions and infer additional local variables from those.
(It's not technically impossible to do that, it just takes our already
complex name scoping rules, and makes them even more complex and hard
to understand).

So in order to do what you want, you're going to need to explicitly
declare a local variable in the scope you want to write to, either by
assigning None to it (in any version), or by using a variable
annotation (in 3.6+). Future readers of your code will thank you for
making the widget definitions easier to find, rather than having them
scattered through an arbitrarily large number of nested functions :)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list