Calling a function of a module by using its name a string

0 votes
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo, and I have a string whose content is "bar". What is the best way to call foo.bar()?

I need to get the return value of the function, which is why I don't just use eval. I figured out how to do it by using eval to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
Nov 25, 2020 in Python by Rajiv
• 8,870 points
589 views

1 answer to this question.

0 votes

Assuming module foo with method bar:

import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()

You could shorten lines 2 and 3 to:

result = getattr(foo, 'bar')()

if that makes more sense for your use case.

You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.

answered Nov 25, 2020 by Gitika
• 65,770 points

Related Questions In Python

+2 votes
1 answer

How can I record the X,Y limits of a displayed X,Y plot using the matplotlib show() module?

A couple hours after posting this question ...READ MORE

answered Dec 27, 2018 in Python by anonymous
1,138 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,422 views
0 votes
1 answer
0 votes
1 answer

How to import a module given its name as string?

With Python older than 2.7/3.1, that's pretty ...READ MORE

answered Nov 25, 2020 in Python by Gitika
• 65,770 points
1,017 views
+1 vote
4 answers

how to sort a list of numbers without using built-in functions like min, max or any other function?

Yes it is possible. You can refer ...READ MORE

answered Jun 27, 2019 in Python by Arvind
• 3,050 points
188,415 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP