A. Wilson
A. Wilson

Reputation: 8840

Package Import woes in Python

My structure is thus:

companynamespace/
  __init__.py
  projectpackage/
    __init__.py
    somemodule.py

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.

Upvotes: 5

Views: 365

Answers (2)

vartec
vartec

Reputation: 134611

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.

Upvotes: 5

user405725
user405725

Reputation:

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.

Upvotes: 1

Related Questions