Name resolution and the (wrong?) LEGB rule

Marco Buttu marco.buttu at gmail.com
Thu Dec 8 09:51:48 EST 2016


Sometimes the Python name resolution is explained using a LEGB rule.
For instance, in [1] (I think also the Learning Python book gives the same):

"if a particular name:object mapping cannot be found in the local 
namespaces, the namespaces of the enclosed scope are being searched 
next. If the search in the enclosed scope is unsuccessful, too, Python 
moves on to the global namespace, and eventually, it will search the 
built-in namespace (side note: if a name cannot found in any of the 
namespaces, a NameError will is raised)."

AFAIK, Python has static scoping: the scope for a name is given during 
the bytecode compilation. This means that before executing the program, 
Python already know in which namespace to look for an object. So, it 
seems to me that the LEGB rule is wrong, and this is what actually happens:

* local name (LOAD_FAST instruction): Python looks (only) in the local 
namespace, and if it does not find the name, then it raises an 
UnboundLocalError

* global name (LOAD_GLOBAL): at first Python looks in the globals(), and 
in case the name is not there, it looks in the builtins namespace; if 
the name is neither in the global nor in the builtin namespace, it 
raises a NameError

* enclosing scope (LOAD_DEREF): there is a closure, and Python looks for 
the name in the enclosing namespace

Is that right, or am I missing something? Thanks, Marco

[1] 
http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html

-- 
Marco Buttu

INAF-Osservatorio Astronomico di Cagliari
Via della Scienza n. 5, 09047 Selargius (CA)
Phone: 070 711 80 217
Email: mbuttu at oa-cagliari.inaf.it



More information about the Python-list mailing list