grg-n-sox
grg-n-sox

Reputation: 717

How do I make relative importing work in Python using Eclipse with PyDev?

So I am working on a Python project that was here before me in an SVN repo. When I first pulled it, the structure was a bit odd due to the fact that it was similar to:

Proj\
    src\
    tags\
    trunk\

And then everything is inside src\ are the python module files except src\ turns out to just be a logical folder with no overall package inside. There isn't a __init__.py in the project anywhere. So I want to restructure it at least so I can use relative imports through my project. I also want to set it up so it looks more like this.

Proj\
    src\
        model\
        controller\
        view\
        test\
    tags\
    trunk\

However, I tried setting this up and no matter what I seem to do, it cannot resolve the relative import the moment I have to traverse packages. I placed a __init__.py file in each level package including one inside the src\ folder with all of them having __all__ defined. However, when I try to make a unit test in my test\ package and do an import saying:

from ..model.foo import Foo

to attempt to import the Foo class from module foo.py located inside of the model package, it doesn't resolve. Just in case it was a problem specifically with unit tests, I also tried this with a module in the controller package that was dependent on a class in the model package and vice versa. None of them worked. How do I resolve this?

Upvotes: 2

Views: 1762

Answers (1)

Jonathan Livni
Jonathan Livni

Reputation: 107192

Have you added the root folder to your system path?

import sys
sys.path.append(<place the Proj dir here>)

then you could import as follows:

from src.model.somefile import Something

If you don't know the absolute path for Proj, you can always use combinations such as

os.path.dirname(os.getcwd())

Upvotes: 3

Related Questions