On Fri, Dec 9, 2016 at 5:03 AM, Peter Otten <__pete...@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() 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? ChrisA -- https://mail.python.org/mailman/listinfo/python-list