92

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?

1

1 Answer 1

90

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

Sign up to request clarification or add additional context in comments.

6 Comments

What about accessing script_b?
What is ... mean?
@mrgloom It means move up two directories: current dir: . up one dir: .. up two dirs: ....
import ...utility_functions.plot_figures as plotfgs ^ SyntaxError: invalid syntax Python shows a syntax error for ...
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.