Question

I always struggled with Python package import. I searched the web, but wasn't able to find an appropriate answer.

I have the following directory structure:

.
./__init__.py
./packages/
./packages/__init__.py
./packages/package
./packages/package/__init__.py
./packages/package/module.py

The module.py source contains only one line:

import package

If I go to "packages" directory, I am able to import package:

>>> import python
>>>

If I go to "." directory, I would like to import the module (or the package) as follow:

>>> import packages.package.module as module

but i'm getting the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "vendor/package/module.py", line 1, in <module>
    import package
ImportError: No module named package

What do I need to put in the __init__.py files, so I can do the above import? More, what do I need to put in ./__init__.py file, so I will able to import my project from ../ directory?

If possible, I would like to solve this problem without changing the sys.path variable.

Was it helpful?

Solution 2

When running the program from . all imports have to be relative to that directory. For your module.py file that means that you have to do

import packages.package

instead of

import package

This is because python will use . as the base for all imports that you do in your program. Without a lot of magic it is not possible to import something from a parent directory, so you will have to do an absolute import as shown above.

OTHER TIPS

In order for the import package in module.py to succeed, the python package package must be discoverable. This means it must be on the PYTHONPATH. By default this path includes site-packages (the directory in which python packages are placed with easy_install or pip). Further, PYTHONPATH also includes the current working directory.

If you are in ., then . is placed at the start of your PYTHONPATH. This directory does not include a python package called package, thus import package fails.

You can either move to ./packages before starting a python interpreter or you can install your package. To do the latter, you'll need a setup.py

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top