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()

Reference

  • 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.
(default) 11 queries took 3 ms
NrQueryErrorAffectedNum. rowsTook (ms)
1DESCRIBE `posts`17171
2DESCRIBE `comments`11110
3DESCRIBE `tags`221
4DESCRIBE `categories`220
5DESCRIBE `posts_tags`220
6DESCRIBE `categories_posts`221
7SELECT `Post`.`id`, `Post`.`url`, `Post`.`title`, `Post`.`icon`, `Post`.`metadesc`, `Post`.`metakeys`, `Post`.`categories`, `Post`.`tease`, `Post`.`body`, `Post`.`private_body`, `Post`.`created`, `Post`.`modified`, `Post`.`status`, `Post`.`allow_comments`, `Post`.`tags`, `Post`.`hitcount`, `Post`.`hitcount_rss` FROM `posts` AS `Post` WHERE `Post`.`url` = 'dynamic-module-loading-with-python-import' LIMIT 1110
8SELECT `Comment`.`id`, `Comment`.`post_id`, `Comment`.`body`, `Comment`.`author`, `Comment`.`url`, `Comment`.`email`, `Comment`.`ip`, `Comment`.`status`, `Comment`.`junk_score`, `Comment`.`created`, `Comment`.`modified` FROM `comments` AS `Comment` WHERE `Comment`.`status` = 2 AND `Comment`.`post_id` = (54) 000
9SELECT `Tag`.`id`, `Tag`.`tag`, `PostsTag`.`post_id`, `PostsTag`.`tag_id` FROM `tags` AS `Tag` JOIN `posts_tags` AS `PostsTag` ON (`PostsTag`.`post_id` = 54 AND `PostsTag`.`tag_id` = `Tag`.`id`) 110
10SELECT `Category`.`id`, `Category`.`category`, `CategoriesPost`.`post_id`, `CategoriesPost`.`category_id` FROM `categories` AS `Category` JOIN `categories_posts` AS `CategoriesPost` ON (`CategoriesPost`.`post_id` = 54 AND `CategoriesPost`.`category_id` = `Category`.`id`) 110
11UPDATE `posts` AS `Post` SET `Post`.`hitcount` = Post.hitcount + 1 WHERE `Post`.`id` = 5410