How to accomplish relative import in python

After fiddling with it a bit more, I realized how to set it up, and for the sake of specificity I won't use foo bar names. My project directory is set up as...

tools/
    core/
        object_editor/
            # files that need to use ntlib.py
            editor.py # see example at bottom
            __init__.py
        state_editor/
            # files that need to use ntlib.py
            __init__.py
        ntlib.py
        __init__.py # core is the top level package
    LICENSE
    state_editor.py # equivalent to main.py for the state editor
    object_editor.py # equivalent to main.py for the object editor

A line in object_editor.py looks like...

from core.object_editor import editor

A line in editor.py looks like...

from .. import ntlib

or alternatively

from core import ntlib

The key is that in the example I gave in the question, the "main" script was being run from within the package. Once I moved it out, created a specific package (core), and moved the library I wanted the editors to share (ntlib) into that package, everything was hunky-dory.


though as long "stuff" is not in your python PATH you got no choice than adding the path.

If you know the level of your script.py from stuff you can do for example:

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))

I'm running Python 3.4.2 on Windows 7 and tore my hair out over this.

When running either of these:

python -m unittest python -m unittest discover

...I would get the 'Attempted relative import beyond toplevel package' error.

For me, the solution was dropping the ".." in my [test_stock.py]. The line was: from ..stock import Stock

Changed it to: from stock import Stock

.. and it works.

Folder structure:

C:\
  |
  +-- stock_alerter
             |
             +-- __init__.py
             +-- stock.py
             |
             \-- tests
                   |
                   +-- __init__.py
                   \-- test_stock.py