Python can't find my custom module in a folder with __init__.py

Viewed 1145

Although there are multiple posts on stack overflow about custom module not found error, but those solutions (such as this one) didn't help in my case.

My folder structure is like this:

project
|-- app
|   |-- script.py
|-- src
|   |-- __init__.py
|   |-- file.py

In my script.py I have this code

import pandas as pd
import streamlit as st
from project.src.file import func

Using VS Code in a windows7 machine, I changed the directory to project, and activated a conda virtual environment, then executed the code streamlit run app\script.py, I got this error

ModuleNotFoundError: No module named 'project'

Changing the script to from src.file import func caused this error

ModuleNotFoundError: No module named 'src'

Could someone please explain what happened? Why Python couldn't find my custom module even though I had the required __init__.py in the folder src.

2 Answers

You need to change the import in script.py to

from src.file import func

and run it in the project directory using

python -m app.script

Since you're using streamlit and apparently it doesn't support running modules, you can try the method provided in this Github issue:

  1. Create a file named run.py inside your project directory with the following contents:
import runpy

runpy.run_module("app.script", run_name="__main__", alter_sys=True)
  1. Run the streamlit command:
streamlit run run.py

Turned out that the python interpreter in my VS Code didn't know the path of my project folder.

Following this suggestion, I set the PYTHONPATH in my VS Code as follows:

set PYTHONPATH=%PYTHONPATH%;path\to\the\folder\project

with the code in script.py as from src.file import func.

the command streamlit run app\script.py then worked without errors.

Related