- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
>>> result = locals()["myfunction"]() or >>> result = globals()["myfunction"]()
- How to import a single function from a Python module?
- How to call a function from a string stored in a variable PHP?
- How to get a function name as a string in Python?
- How to call a function with argument list in Python?
- How to Call a Lua function from C?
- How to call a function inside a jQuery plugin from outside?
- How to call a parent class function from derived class function in C++?
- Maximum length of consecutive 1’s in a binary string in Python using Map function