Name resolution and the (wrong?) LEGB rule

Peter Otten __peter__ at web.de
Thu Dec 8 14:14:09 EST 2016


Chris Angelico wrote:

> On Fri, Dec 9, 2016 at 5:03 AM, Peter Otten <__peter__ at web.de> wrote:
>>> The "usual optimization" is exactly what you describe: that different
>>> bytecodes represent Local, Enclosing, and Global/Built-in scope
>>> lookups. (Globals can be created or removed at run-time, so there's no
>>> optimization possible there.) But in terms of language specifications,
>>> the lookup rules are the same; it's just that the CPython compiler
>>> takes advantage of information that it can see ("these are the only
>>> locals for this function") to speed up execution.
>>
>> If it is only an optimization why doesn't a failing local lookup fall
>> back to the global namespace?
> 
> Define "failing". Do you mean that this should print "outer"?
> 
> x = "outer"
> def f():
>     print(x)
>     x = "inner"
> f()

I mean it could, as classes already work that way. I think the current 
behaviour is a design decision rather than an implementation accident.
 
> There are plenty of languages where this is true, but they work
> because the defined scope of a variable is "from its declaration
> down". Python doesn't work like that. Neither does JavaScript,
> although it's a bit bizarre in a few ways. The lookup doesn't fail; it
> finds a local variable that doesn't have a value. At least, I'm pretty
> sure that's how it works. Is there a language specification stating
> this?

I found

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




More information about the Python-list mailing list