0

I have the following project structure

.
├── app
│   ├── main.py
│   ├── foo.py
│   └── bar.py
├── Dockerfile
├── input
│   ├── data
├── output
├── README.md
├── requirements.txt
└── rest_api.py

And my Dockerfile

FROM python:3.9-slim

# install require OS packages
# we use apt-get instead of apt because of the stable CI
RUN apt-get update && \
    apt-get install --no-install-recommends -y build-essential gcc git && \
    apt-get clean && rm -rf /var/lib/apt/lists/* && \
    pip3 install --upgrade pip

# define and create working directory
WORKDIR /usr/application

COPY /requirements.txt .
RUN pip3 install --no-cache-dir -r requirements.txt

COPY / .

ENV PYTHONUNBUFFERED=TRUE
CMD ["python3", "rest_api.py", "--environment-config-file", "/..."]

The file api_rest.py calls submodules with from app.main import main as in that seems to work. However, in main.py, using the syntax from foo import * raises ModuleNotFoundError.

Being in the same folder, why is this happening and how can I resolve the issue?

Norhther
  • 545
  • 3
  • 15
  • 35
  • With that file structure, I'd expect all of your Python packages to be under an `app` hierarchy; for example, `app.main` or `app.foo`, not just `foo`. Does this work successfully without Docker in a plain-Python virtual environment? – David Maze Feb 28 '23 at 11:53
  • @DavidMaze do you mean using `app.foo` inside `/app/main.py`? – Norhther Feb 28 '23 at 15:07
  • Yes. Unqualified `foo` would refer to a `foo.py` file in the top-level directory, outside the `app` directory. Again, you should be able to see the same behavior in a non-Docker virtual environment, and this will be easier for you to debug. – David Maze Feb 28 '23 at 15:08
  • @DavidMaze I thought that, if the file was in the same folder, you could call it without specifying the package, because was in the same directory. But instead, it seems that you have the specify always te path respect the top-level directory? Is this a regular behaviour from docker or python? – Norhther Feb 28 '23 at 15:15
  • This is Python; running it in Docker has no bearing on how it works. See for example [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) which has a very detailed answer of what you can `import`. – David Maze Feb 28 '23 at 17:40

0 Answers0