Suppose we have a hash table that maps strings to functions. In my example I’ll call it COMMANDS. If I place the definition for some function (let’s call it cmd_add) after the hash table that maps it to a string, and then I attempt to invoke it, I get an error:
COMMANDS = {'add': cmd_add}
def cmd_add():
print 'ADD'
COMMANDS['add']()
# NameError: name 'cmd_add' is not defined
Now notice that if I simply move the function definition to before the definition of COMMANDS, it works out just fine:
def cmd_add():
print 'ADD'
COMMANDS = {'add': cmd_add}
COMMANDS['add']()
# NO ERROR!
Why is this true? Is there something about Python binding that I do not understand?
Remember that Python is a dynamic language, even though cmd_add is a reference to a function in your source there is nothing stopping it from referring to a different object at different times.
Python will creating the binding as the interpreter passes the line where the function is defined and it will reference that function until you delete the reference or rebind it to something else