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 TextPython code
- version_number = 2
- module_name = "string" + str(version_number)
- var_module = __import__(module_name)
- var_module.RunMe()
Reference
- A full definition of the import statement can be found on this page python.org.