Could someone, please, explain in plain English what exactly and why is going on in this little snippet:
def foo():
print "You are calling a function via a variable"
var='foo'
fun_var = globals()[var]
print fun_var # it says `<function list>`
print type(fun_var) # it says `<type 'function'>`
fun_var() # it actually prints out "You are calling a function via a variable"
I understand that via some magic globals() takes the value of var and creates a function with the same name as the value. I also do understand that this may be quite a nice workaround if we don't know the value of var (e.g., it may be set by a user) and we have some functions, one of which we'd like to call depending on that value (e.g. according to the user's preferences).
However, the whole process still looks to me a bit like miracle :). What exactly globals() does here? Where do these powers are coming from? :)
Thank you.
globals(), lest you decide to use it for something in the future.