1

There are 10+ SO posts about this already, none of the answers works for me and I still haven't seen an example of someone importing something from a sibling directory.

src
    __init__.py
    test.py
    package1
        __init__.py
        module1.py
    package2
        __init__.py
        module2.py

(_init_.py should not be necessary on python versions greater than 3.3 but I still have them there as they make no difference)

in test.py I have

import package1.module2

and it works fine however the problem is when I want to import something from package2 to package1, and vice versa. I have tried different import methods in module2.py and I receive these different error messages:

import src.package1.module1.py

with the error:

ModuleNotFoundError: No module named 'src'

and

from .. import package1

with the error:

ImportError: attempted relative import with no known parent package

The top answer here: How do I import a Python script from a sibling directory? also give me the exact error message as I showed above. The answers here: How to import a Python module from a sibling folder? changes nothing. Am I missing something or should it not be possible to import stuff between different folders/packages? Do I need the "sys.path hack"?

lapurita
  • 338
  • 1
  • 2
  • 9
  • How are you running your code? – Brian Dec 17 '21 at 15:33
  • 1
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Brian Dec 17 '21 at 15:33
  • I guess... Not really a solution but it explains why it is not possible to structure my code this way. From what I understand I can't run scripts directly in a subdirectory that uses something from another subdirectory – lapurita Dec 17 '21 at 19:05
  • 1
    Yes and no. Directories and subdirectories are meaningless to Python. All Python cares about are modules and packages, which are searched for exclusively on the Python path. You can certainly run modules from wherever you want inside of a package, but you need to remember to tell Python where in the package that module is / where the package(s) you want to import are. – Brian Dec 17 '21 at 19:09

0 Answers0