Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function from string inside the same module in Python?

Tags:

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?

like image 465
prashu Avatar asked Oct 11 '12 18:10

prashu


People also ask

How do you call a function inside a string in Python?

Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.

How do you call a function from a module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

Can you call a function within the same function Python?

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

How do you call a function in string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.


2 Answers

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.

like image 176
mgilson Avatar answered Sep 23 '22 18:09

mgilson


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

if __name__ == '__main__':   funcnames = {'bar': bar}   funcnames['bar']() 
like image 38
Ashwini Chaudhary Avatar answered Sep 20 '22 18:09

Ashwini Chaudhary