Objects in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Aug 26 10:18:58 EDT 2012


On Sun, 26 Aug 2012 23:58:31 +1000, Chris Angelico wrote:

> On Sun, Aug 26, 2012 at 11:43 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> It gets worse: Python has multiple namespaces that are searched.
>>
>> "Go to the Excelsior Hotel and ask the concierge for Mr Smith. If Mr
>> Smith isn't staying there, go across the road to the Windsor Hotel and
>> ask there. If he's not there, try the Waldorf Astoria, and if he's not
>> there, try the Hyperion."
> 
> Does it? I thought the difference between function-scope and
> module-scope was compiled in,

It is. But local and global scope are not the only two scopes. Python has 
nested scopes. Try these:

x = y = -99
def test():
    def inner():
        x = 23
        def even_more_inner():
            print "x is", x
            print "y is", y
        even_more_inner()
    x = 1000
    y = 42
    inner()

Also, built-ins require a name lookup too. As you point out, locals are 
special, but Python will search an arbitrarily deep set of nested 
nonlocal scopes, then globals, then builtins.

See the introduction of nested-scopes:

http://www.python.org/dev/peps/pep-0227/

and non-locals:

http://www.python.org/dev/peps/pep-3104/


-- 
Steven



More information about the Python-list mailing list