Python relative-import script two levels up

Luke Taylor picture Luke Taylor · Apr 24, 2016 · Viewed 34.2k times · Source

I've been struggling with imports in my package for the last hour.

I've got a directory structure like so:

main_package
 |
 | __init__.py
 | folder_1
 |  | __init__.py
 |  | folder_2
 |  |  | __init__.py
 |  |  | script_a.py
 |  |  | script_b.py
 |
 | folder_3
 |  | __init__.py
 |  | script_c.py

I want to access code in script_b.py as well as code from script_c.py from script_a.py. How can I do this?

If I put a simple import script_b inside script_a.py, when I run

from main_package.folder_1.folder_2 import script_b

I am met with an

ImportError: no module named "script_b"

For accessing script_c.py, I have no clue. I wasn't able to find any information about accessing files two levels up, but I know I can import files one level up with

from .. import some_module

How can I access both these files from script_a.py?

Answer

tobspr picture tobspr · Apr 24, 2016

To access script_c and script_b from script_a, you would use:

from ...folder_3 import script_c
from . import script_b

Or if you use python3, you can import script_b from script_a by just using:

import script_b

However, you should probably use absolute imports:

from mypackage.folder_3 import script_c
from mypackage.folder1.folder2 import script_b

Also see: Absolute vs Relative imports