Objects in Python
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Aug 26 18:47:36 EDT 2012
On Mon, 27 Aug 2012 00:54:05 +1000, Chris Angelico wrote:
> On Mon, Aug 27, 2012 at 12:18 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> 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.
>
> Ah, builtins, forgot that. So yes, global scope involves potentially two
> name lookups. But nonlocals aren't searched at run time.
Well, whaddyaknow. You're right.
x = 'globals'
def test(switch):
def a():
if switch == 1:
x = 'a'
def b():
if switch == 2:
x = 'b'
def c():
print "x found in", x
c()
b()
a()
Tried that in Jython, IronPython and Python 2.7, and I get the same
result: only test(2) succeeds.
I even tried it in Python 2.2, which does the same thing.
(2.1 and older don't have nested scopes, so there's no point in going
back further.)
--
Steven
More information about the Python-list
mailing list