[Python-ideas] Unify global and nonlocal

Manuel Cerón ceronman at gmail.com
Mon Feb 3 21:27:08 CET 2014


Hello,

The 'global' and 'nonlocal' statements serve very similar purposes.
They both allow to rebind names in an outer scope. While 'nonlocal'
allows to rebind a name in the closest outer scope, *except* the
global module scope, 'global' is used for the later case.

Is there a reason why 'nonlocal' has to stop at the scope immediately
after the global module scope? If 'nonlocal' could continue until the
global scope, then it would become (almost) a generalized case of
'global'. Having both statements goes against the "There should be one
- and preferably only one - obvious way to do it" principle.  It's
also confusing for beginners and people used to a functional style.

I think 'nonlocal' should be changed to support all the enclosing
scopes, including the global module scope, and the 'global' statement
should be marked as deprecated.

There is one specific use case that breaks though, which is rebinding
to global names from a deep function skipping names in the middle, for
example:

x = 'global'
def outer1():
    x = 'outer1'
    def outer2():
        global x
        x = 'outer2' # binds the global module name

But you know "special cases aren't special enough to break the rules".

My apologizes if this topic was already discussed in the past.

Manuel.


More information about the Python-ideas mailing list