[Python-ideas] Nonlocal oddness
Carl Johnson
carl at carlsensei.com
Mon Oct 6 08:26:59 CEST 2008
I noticed something based on some code in the other thread, but it's
not really related to it. Is there a reason for this not working:
>>> i = 0
>>> def f():
... nonlocal i
... i += 1
... return lambda: i
...
SyntaxError: no binding for nonlocal 'i' found
Versus:
>>> i = 0
>>> def f():
... global i
... i += 1
... return lambda: i
...
>>>
This was probably already discussed at the time "nonlocal" was
invented, but is there a specific reason that "nonlocal" can't be used
in cases where the next scope out is the same as "global"? I naively
assumed that you could use them almost interchangeably if you were at
the top level of a module. ("Almost" because "global" adds the
variable to the module namespace if it's not already there, whereas
"nonlocal" doesn't blithely add variables to other scopes, but just
goes looking for existing ones.) Why force me to switch to "global"
when I cut and paste a function out of a class or whatever and put it
at the top level of my module? Is it just so that TOOOWTDI? Or was it
an oversight? Or is there some other reason?
Thanks,
-- Carl
More information about the Python-ideas
mailing list