+2 votes
2 views
in Python by (4.1k points)
edited by

Can someone tell me how can I Call a function in a string with function name in python program? E.x. Let's assume I have a module foo and a string with content "bar". So what can I do to call foo.bar()?

I know how to do this by using eval but I am looking for some another better method because I want a return value of the function and that's why I can't use it. I just want more efficient way to perform this task. 

2 Answers

0 votes
by (46.1k points)
edited by

You can use locals which returns a current local symbol table or you can use globals which returns a dictionary with global symbol table.

locals()["myfunction"]()


globals()["myfunction"]()

Happy Learning. Cheers..!! 

0 votes
by (107k points)

If you need to dynamically pick up the module, you can import it like as follows:

module = __import__('foo')

func = getattr(module, 'bar')

func()

You can use the following video tutorials to clear all your doubts:-

Related questions

+2 votes
3 answers
asked May 24, 2019 in Python by Suresh (3.4k points)
0 votes
1 answer
asked Jul 6, 2019 in Python by Sammy (47.8k points)
+1 vote
2 answers
+2 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...