Wednesday, June 3, 2015

Use string variable or string to call a function

In python locals() return a dictionary representing the current local symbol table with all functions as dictionaries.
Say you have a function called  "Func()". The locals() will return a dictionary with "Func" as shown below:
{....., 'Func': <function Func at 0x7f9ff50a5268>, ...........}
Now you can the call the function 'Func()' by the calling the dictionary key as below:

Direct String Substitution:
     locals() ['Func'] ()

Variable Substitution:
    F = "Func"
    locals() ['F']

 You can also use globals() instead of locals() if you need global system table. 

If the function is part of a class then use getattr(class,"function")()