
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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"]()
- Related Articles
- How to call a function of a module from a string with the function's name in Python?
- How to call a function from its name stored in a string using JavaScript?
- 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 call Python module from command line?
- How to call a function with argument list in Python?
- How to get a function name as a string in Python?
- How to turn a String into a JavaScript function call?
- How do I call a Variable from Another Function in Python?
- How to call a JavaScript function from C++?
- How to Call a Lua function from C?
- User rights required to make a call to SAP RFC Function Module RFC_SYSTEM_INFO from JAVA application
- How to call a JavaScript Function from Chrome Console?
- How to call a function inside a jQuery plugin from outside?
- How to call a function with Mouse hover in VueJS?

Advertisements