0

Since I've never had scripts big enough to need sub directories, I'm pretty new to packages and importing from different directories in python. Is importing from sibling and/or parent directories not allowed in python (3.8.6)?

In the following structure:

parent_dir/
parent_dir/__init__.py
parent_dir/parent.py
parent_dir/sub_dir1/__init__.py
parent_dir/sub_dir1/sub1.py
parent_dir/sub_dir2/__init__.py
parent_dir/sub_dir2/sub2.py

In the sub1.py file, I tried:

from sub_dir2 import sub2

I ended up getting the following:

ModuleNotFoundError: No module named 'sub_dir2'

If I try relative imports in the sub_dir1/init.py file:

from .import sub1

I get:

ImportError: attempted relative import with no known parent package

What am I doing wrong?

Vedank Pande
  • 436
  • 3
  • 10
  • One common problem is that all your code is fine, but you are trying to run the code from inside the package directory. – Karl Knechtel Mar 28 '21 at 07:27
  • Hi there and welcome on StackOverflow. Questions regarding relative imports have been answered a couple of times already. When in `sub_dir1/__init__.py `: Sibling import: `from .sub1 import $export`. Parent import: `from ..parent import $export`. – Lukas Bünger Mar 28 '21 at 07:30
  • Relative imports are not a directory traversal mechanism. – user2357112 Mar 28 '21 at 07:33
  • Thanks everyone, running the scripts from outside the package worked, although I'm running into a slight problem with pylint while doing this. It says unable to import this package when I hover over the red squiggly lines, but when I run the code it works. How do I get rid of these and why are they showing up? – Vedank Pande Mar 28 '21 at 09:28

0 Answers0