Python module not imported despite file being there

30 Views Asked by At

I have a python project. I have activated virtualenv for it and installed requirements.txt

Here is my files/dirs structure

.
├── app
│   ├── app.py
│   ├── modules
│   │   ├── __pycache__
│   │   ├── foo.py
│   │   ├── settings.py
│   └── requirements.txt

I am doing the following import in foo.py

import settings

VSCode does not complain (while in other erroneous import attempts it did complain)

enter image description here

When trying to run the program

▶ python app/app.py 
Traceback (most recent call last):
  File "/path/to/project/app/app.py", line 1, in <module>
    from modules import foo
  File "/path/to/project/app/modules/foo.py", line 14, in <module>
    import settings
ModuleNotFoundError: No module named 'settings'
(.venv) 

What am I missing?

1

There are 1 best solutions below

1
Emil On BEST ANSWER

Python modules are not imported relatively out-of the box.

In foo.py, you can import `settings' using:

from . import settings
# ...

@pkaramol : in older versions of python it was necessary to create __init__.py inside modules directory to be able to use this syntax, but at least in python3.10 it is not.