79

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?

Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
  • Possible duplicate of [How to accomplish this relative import in python](http://stackoverflow.com/questions/4655526/how-to-accomplish-this-relative-import-in-python) – Ani Menon Apr 24 '16 at 18:04

1 Answers1

78

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

Community
  • 1
  • 1
tobspr
  • 8,200
  • 5
  • 33
  • 46
  • 1
    What about accessing `script_b`? – Luke Taylor Apr 24 '16 at 18:03
  • 3
    What is `...` mean? – mrgloom Sep 11 '19 at 13:50
  • 14
    @mrgloom It means move up two directories: current dir: `.` up one dir: `..` up two dirs: `...`. – Adam Erickson Jan 22 '20 at 21:57
  • 1
    `import ...utility_functions.plot_figures as plotfgs ^ SyntaxError: invalid syntax` Python shows a syntax error for ... – Aaron John Sabu Jul 21 '21 at 11:47
  • 2
    It doesn't work for me: Having `from ...folder_3 import script_c` in `script_a.py` and running it `python script_a.py` gives me `ImportError: attempted relative import with no known parent package`. I'm using Python 3.7. – Lei Mar 17 '23 at 01:53
  • @Lei, you can't use _relative_ imports in `script_a.py` when running `python script_a.py`. You can get rid of the relative import and either `cd ../../ && python $OLD_PWD/script_a.py` or `PYTHONPATH=../../ python script_a.py` or create a top-level script and turn the old script into a module – CervEd Sep 01 '23 at 15:44