How would you dynamically import a module if you have the module’s name stored in a string variable?
- import moduleName from 'modulePath'
- import(moduleName as 'modulePath')
- import(moduleName)
- import(moduleName, 'modulePath')
To dynamically import a module when you have the module's name stored in a string variable, you would use:
import(moduleName)
However, this isn't directly valid syntax in Python.
The recommended way for Python 2.7 and 3.1 and later is to use importlib
module:
import importlib
module = importlib.import_module(moduleName)
With Python older than 2.7/3.1, using __import__
you can import a list of modules by doing this:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
Loading...
Related Quiz
- What would be the result of attempting to import a module that does not exist?
- What's the primary difference between from module import * and import module as alias?
- A ____ is a linear data structure where the elements are arranged in a circular fashion.
- You are implementing a function to calculate the factorial of a number. Which Python built-in data type would be most suitable to store the result for very large numbers?
- What can be a potential pitfall of overusing @property decorators in a Python class?