We can see the NameError
and UnboundLocalError
at runtime when the name is not defined and unbound respectively. But it is not clear how does name evaluating occuring at run time? I assume the following:
Consider example of code snippet
def foo():
a=3
def bar():
return a
tmp=bar()
res=a+tmp
return res
When bar
function is invoked we have that new execution frame is created. Denote this frame as bar_frame
. There is no elements contained in an bar_frame.f_local
dictionary. But bar_frame.f_back.f_locals
contains 4 name-value pairs. And so
My understanding: We have the following algorithm of name evaluation:
Trying to find
name
in thecurrentframe.f_locals
1.1 If
currentframe.f_locals
corresponding to a global namespace and suitable name is not found then throwNameError
1.1 If suitable name is found and it is bounded then return
currentframe.f_locals[name]
1.2 If suitable name is found and it is unbounded throw
UnboundLocalName
error.Trying to find
name
in thecurrentframe.f_back.f_locals
Please check my understanding.