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)

Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *