I have a messages folder(package) with __init__.py
file and another module messages_en.py
inside it. In __init__.py
if I import messages_en
it works, but __import__
fails with "ImportError: No module named messages_en"
import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
I used to think 'import x' is just another way of saying __import__('x')
If it is a path problem, you should use the
level
argument (from docs):__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:On the other hand, the statement
from spam.ham import eggs, sausage as saus
results inmore info: http://docs.python.org/library/functions.html
Be sure to append the modules directory to your python path.
Your path (the list of directories Python goes through to search for modules and files) is stored in the path attribute of the sys module. Since the path is a list you can use the append method to add new directories to the path.
For instance, to add the directory /home/me/mypy to the path:
You need to manually import the top package of your dynamic package path.
For example in the beginning of the file i write:
then later in code this works for me:
Adding the globals argument is sufficient for me:
In fact, only
__name__
is needed here:You could try this: