Calling a function of a module from a string with the function\'s name in Python

Answer

Assuming module foo with method bar:

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

As far as that goes, lines 2 and 3 can be compressed 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.

All python Questions

Ask your interview questions on python

Write Your comment or Questions if you want the answers on python from python Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---