- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to call a function of a module from a string with the function's name in Python?
Objects in python have instance variables and methods as attributes. To call a function of a module from a string with the function's name in Python, you can get this attribute first and call the function object attached to it. For example, let's say that I have a module foo, and I have a string whose contents are "bar". The best way to go about calling foo.bar() is:
>>> import foo >>> method_to_call = getattr(foo, 'bar') >>> result = method_to_call()
If you have the function in global or local namespace without the module prefix, you can also use globals()/locals(). locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
For example
>>> result = locals()["myfunction"]() or >>> result = globals()["myfunction"]()
Advertisements