Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 263
A. Wilson Avatar asked Apr 26 '11 21:04

A. Wilson


1 Answers

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.

like image 80
vartec Avatar answered Oct 10 '22 00:10

vartec