[Python-ideas] Nonlocal oddness

Brett Cannon brett at python.org
Mon Oct 6 08:44:40 CEST 2008


On Sun, Oct 5, 2008 at 11:26 PM, Carl Johnson <carl at carlsensei.com> wrote:
> 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"?

Because nonlocal is not global. The whole point of nonlocal is it
falls between global and 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?
>

You said it already: "cut and paste". Having nonlocal != global helps
catch some potential bugs. Plus you just don't gain anything worth
losing that assistance in finding coding errors by having nonlocal act
like global.

-Brett



More information about the Python-ideas mailing list