Asked • 06/17/19

Calling a function of a module by using its name (a string)?

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.

1 Expert Answer

By:

Matthew B. answered • 11/12/19

Tutor
5.0 (62)

Founder, CEO, and Lead Developer: Apteryx Labs | Stanford, 2015

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.