[Python-ideas] Unify global and nonlocal

Andrew Barnert abarnert at yahoo.com
Mon Feb 3 21:47:56 CET 2014


On Feb 3, 2014, at 12:27, Manuel Cerón <ceronman at gmail.com> wrote:

> 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.

In my experience dealing with people coming to python from functional languages, they generally want closure variables to be as restricted as possible, and it's actually the fact that you can use a global as a closure variable _at all_ that they find confusing, not the fact that the syntax and semantics are a bit different than for a local closure variable. 

In fact, there was a question on StackOverflow a few weeks ago from someone who wanted to know how this could possibly work:

    a = []
    def spam():
        return a[0]
    a.append(1)
    print spam.__closure__
    print spam()

(Yes, it was Python 2, and it's an implicit rather than explicit global... But same idea.)

I don't think this change would help people with that kind of confusion at all.

That being said, I don't think it would _hurt_ them, and it would probably help novices learning the concept of closures for the first time, in Python. And it could make some kinds of refactoring easier to mechanize.


More information about the Python-ideas mailing list