28

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?

S.P.
3,0641 gold badge21 silver badges17 bronze badges
asked Oct 11, 2012 at 18:18

2 Answers 2

45

globals is probably easier to understand. It returns the current module's __dict__, so you could do:

func_I_want = globals()['bar'] #Get the function
func_I_want() #call it

If you really want the module object, you can get it from sys.modules (but you usually don't need it):

import sys.modules
this_mod = sys.modules[__name__]
func = getattr(this_mod,'bar')
func()

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.

answered Oct 11, 2012 at 18:19
Sign up to request clarification or add additional context in comments.

Comments

21

Use a dictionary that keeps the mapping of functions you want to call:

if __name__ == '__main__':
 funcnames = {'bar': bar}
 funcnames['bar']()
answered Oct 11, 2012 at 18:20

1 Comment

I always appreciate an answer that solves the OP's problem rather than her/his question. +1

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.