python - Calling a function of a module from a string with the function's name -


what best way go calling function given string function's name in python program. example, let's have module foo, , have string contents "bar". best way go calling foo.bar()?

i need return value of function, why don't use eval. figured out how using eval define temp function returns result of function call, i'm hoping there more elegant way this.

assuming module foo method bar:

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

as far goes, lines 2 , 3 can compressed to:

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

if makes more sense use case. can use getattr in fashion on class instance bound methods, module-level methods, class methods... list goes on.


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -