tags:

views:

1315

answers:

4

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

+4  A: 

__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

Perica Zivkovic
+1 and thanks for explanation, but could you describe exactly why OP's example doesn't work? He seems to be trying to alias messages_en to messages, which seems (naively to me) to be reasonable.
John Pirie
As 'wr' explained it was due to level, and I know __import__ shouldn't be usually used but in this case i have to dynamically read language from a config file append to messages and import that file
Anurag Uniyal
+5  A: 

If it is a path problem, you should use the level argument:

__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.
wr
but I wonder what was the reason , because default level is -1, and I am still passing -1, so only extra are global/local dict, how that makes a difference
Anurag Uniyal
A: 

You could try this:

messages == __import__('Foo.messages_en', fromlist=['messages_en'])
Lennart Regebro
A: 

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:

import sys
sys.path.append("/home/me/mypy") 
Upgrayd