Lets say I have a function bar inside a module called foo.py . Somewhere inside foo.py, I want to be able to call bar() from the string “bar”. How do I do that?
# filename: foo.py
import sys
def bar():
print 'Hello, called bar()!'
if __name__ == '__main__':
funcname = 'bar'
# Here I should be able to call bar() from funcname
I know that there exists some built-in function in python called ‘getattr’. However, it requires ‘module object’ to be the first parameter. How to obtain the ‘module object’ of the current module?
globalsis probably easier to understand. It returns the current module’s__dict__, so you could do:If you really want the module object, you can get it from
sys.modules(but you usually don’t need it):Note that in general, you should ask yourself why you want to do this. This will allow any function to be called via a string — which is probably user input… This can have potentially bad side effects if you accidentally give users access to the wrong functions.