Thursday, August 9, 2012

Python: Import a Submodule Programmatically

Situation:
In Python 2.7, there is a need to import a sub-package programmatically by name.

Problem:
I've looked at __import__ and importlib but the solution is not readily apparent.

Solution:
import importlib
module_name = '.'.join(('os','path'))
path = importlib.import_module(module_name)

#or

import sys

module_name = '.'.join(('os','path'))
__import__(module_name)
path = sys.modules[module_name]

References:
  1.  importlib – Convenience wrappers for __import__()
  2. Source code for importlib





No comments:

Post a Comment