Joril Joril - 1 year ago 73
Python Question

How to do relative imports in Python?

Imagine this directory structure:


I'm coding
, and I need to import something from
. How should I do it?

I tried
from ..sub2 import mod2
but I'm getting an "Attempted relative import in non-package".

I googled around but found only "
manipulation" hacks. Isn't there a clean way?

Edit: all my
's are currently empty

Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (
, etc.).

Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)

Answer Source

Everyone seems to want to tell you what you should be doing rather than just answering the question.

The problem is that you're running the module as '__main__' by passing the as an argument to the interpreter.

From PEP 328:

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.

Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download