Dynamic module loading with Python import

In general python modules are imported in one of the following manners :-

  • import <module_name>
  • from <module_name> import *
  • from <module_name> import <name 1>,...,<name N>

However, lets say you don't know the module name before your program starts or your program needs to dynamically link to a module based on a specific version number. In other words you want a generic way of loading a module dynamically without initially knowing the name of the module before the program starts. This can be done easily in python with the following import syntax :-

  • var_module = __import__("<module_name>")

For example :-

Show Plain Text
Python code
  1. version_number = 2
  2. module_name = "string" + str(version_number)
  3. var_module = __import__(module_name)
  4. var_module.RunMe()


  • A full definition of the import statement can be found on this page python.org.
Filed under: Notes  Tags: Python

0 Responses to “Dynamic module loading with Python import”

Sorry, comments have been closed for this post.