Take the 2-minute tour ×

My structure is thus:


companynamespace/__init__.py is empty

projectpackage/__init__.py has this line:

import companynamespace.projectpackage.somemodule as module_shortname

When I open up a python console and type import companynamespace.projectpackage (PYTHONPATH is set correctly for this), I get AttributeError: 'module' object has no attribute 'projectpackage' on the import companynamespace.projectpackage.somemodule as module_shortname line. If I remove the as module_shortname part (and make all the requisite substitutions in the rest of the file), everything imports correctly.

Can anyone tell me why this is? My Google-Fu fails me.

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

There is no need for absolute import in projectpackage/__init__.py, do relative one

import somemodule as module_shortname

The way you're doing it (with absolute import), would lead to circular import, which don't work very well in Python. When you're importing module, you're also calling __init__.py of parent modules. In your case, with absolute import you're also calling projectpackage/__init__.py in projectpackage/__init__.py.

share|improve this answer
The diagnosis (i.e. a circular import problem) is correct, but the explanation and suggested resolution aren't quite right. When projectpackage/__init__.py is executed, the projectpackage attribute in companynamespace is not yet set, hence the specific error that is raised. For current Python, an explicit relative import (from . import somemodule) is a better choice than relying on an implicit relative import. –  ncoghlan Apr 27 '11 at 5:26
The gory details can be found at bugs.python.org/issue992389 –  ncoghlan Apr 27 '11 at 5:28
Thanks a mil, I'd figured a circular import issue, but had no idea what functionality Python had to solve it. –  A. Wilson Apr 29 '11 at 0:25
add comment

Well, according to the PEP 221 your code seems to be legitimate. It could be a bug. The following workaround, which is equivalent of that expression, works for me (Python 2.6.6):

from companynamespace.projectpackage import somemodule as module_shortname

Hope it helps.

share|improve this answer
add comment

Your Answer


