0

My imports dont show any linting errors (flake8), but generate a ModuleNotFoundError when run.

The application can be started from either __main__.py or bar.py. Both modules call bar.py. The application seems to work when __main__ is called, but I get the following error when running bar:

Traceback (most recent call last):
  File "a:/Git/repo/lib/data/bar.py", line 1, in <module>
    from src.foo import classA
ModuleNotFoundError: No module named 'src'

Directory structure

repo
└── lib
    ├── src
    │   ├── __init__.py
    │   ├── __main__.py
    │   └── foo.py
    ├── data
    │   ├── __init__.py
    │   └── bar.py
    └── __init__.py

main

from foo import classA

foo

class classA:
    def dostuff(x):
        ...

bar

from src.foo import classA 
Hughes
  • 339
  • 3
  • 15

1 Answers1

0

If you are attempting an import from a module, you need to make sure you're giving it context in relation to where the file you're importing is in the structure.

In bar.py you need to note that data is on the same level as src so you must go one level higher before you reference src: from ..src.foo import ClassA. from src.foo as in your question is equivalent to from .src.foo which would be searching for foo inside the data directory.

zganger
  • 3,572
  • 1
  • 10
  • 13
  • I'm now getting ValueError: attempted relative import beyond top-level package – Hughes May 12 '20 at 14:06
  • That is likely based on your PYTHONPATH not referencing the root of the project. This post may help you adjust: https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import – zganger May 12 '20 at 15:12