Where is my import statement pointing to?

Viewed 28

I'm working on a project with the following directory structure:

.
├── main.py
└── modules
    ├── __init__.py
    ├── error
    │   ├── __init__.py
    │   └── friendly_error.py
    └── search
        ├── __init__.py
        └── cog.py       <== The "problem child"

(Non relevant files omitted for brevity)

When running main.py, I get hit with an error in modules/search/cog.py: No module named 'error'

This is the import statement in cog.py causing the error:

from error.friendly_error import FriendlyError

My twofold question is:

  • How can I structure the import statement to direct python to the correct file?
  • Where is python looking, given the current import statement?

It's worth noting that VSCode does not have an issue with the import statements, and when I click on Go to definition of FriendlyError it opens up ./modules/error/friendly_error.py.

1 Answers

I resolved the error by replacing the import with this:

from ..error.friendly_error import FriendlyError

I am still curious to know why this worked and the other one didn't.

Related