Search  


Q&A: Calling a function of a module by using its name?  
Tuesday, April 21, 2020, 11:04 PM
Posted by Administrator
Q: 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.

A: 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.
add comment ( 189 views )   |  permalink   |  $star_image$star_image$star_image$star_image$star_image ( 3 / 593 )

<<First <Back | 1216 | 1217 | 1218 | 1219 | 1220 | 1221 | 1222 | 1223 | 1224 | 1225 | Next> Last>>







Share CertificationPoint & Stay Informed Socially About EduTech?