I understand that this question is about the __import__()
function but I think the importlib
package is best suited for run-time package imports if you are using Python 2.7 or above as advised in the doc:
Note: Programmatic importing of modules should use import_module() instead of this function.
Possible Gotcha: This was introduced in python 2.7:
New in version 2.7.
This module is a minor subset of what is available in the more full-featured package of the same name from Python 3.1 that provides a complete implementation of import. What is here has been provided to help ease in transitioning from 2.7 to 3.1.
In your case, you may use:
import importlib
messages = importlib.import_module('messages_en')
Also, if you wanted to specify the package name, then from messages import messages_en
may be written as:
importlib.import_module('.messages_en', 'messages')
Note the .
in .messages_en
used for relative path resolution as described here:
... The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).