How can I import a package using __import__() when the package name is only known at runtime?
If it is a path problem, you should use the level
argument (from docs):
__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Level is used to determine whether to perform
absolute or relative imports. -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
Adding the globals argument is sufficient for me:
__import__('messages_en', globals=globals())
In fact, only __name__
is needed here:
__import__('messages_en', globals={"__name__": __name__})
__import__
is an internal function called by import statement. In everyday coding you don't need (or want) to call __import__
from python documentation:
For example, the statement import spam
results in bytecode resembling the following code:
spam = __import__('spam', globals(), locals(), [], -1)
On the other hand, the statement from spam.ham import eggs, sausage as saus
results in
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage
more info: http://docs.python.org/library/functions.html