0

I have a project structured as follows:

.
└── MYAPP/
    ├── data/ # contains data files i.e: html/json/db files.
    ├── src/
    │   └── myapp/
    │       ├── __init__.py
    │       ├── core.py
    │       └── utils.py
    └── tests/
        ├── conftest.py
        ├── test_core.py
        └── test_utils.py # contains ClassA and ClassB

conftest.py contains the following:

import pytest
from src.myapp.utils import ClassA, ClassB

as you can see in the contents of conftest.py, I am importing the required classes using an absolute import.

By chance while reading through Flask's source code on github, I saw that they were using a similar project structure:

.
└── flask/
    ├── src/
    │   └── flask
    └── tests

and in test files were not using absolute imports, for example in the conftest.py file they had the following:

import pytest
from _pytest import monkeypatch

import flask
from flask import Flask as _Flask

My question is, How did flask achieve to import its module into test by just using import flask or from flask import Flask as _Flask. when I attempt to do that (import myapp), I end up with ModuleNotFoundError: No module named 'myapp'

Adam
  • 945
  • 1
  • 6
  • 14
  • 1
    `Flask` (or any installed packages) are added to the `site-lib` in python. Your package is not part of this. Instead imports inside a project are either absolute or relative. More information about the import system is in the [docs](https://docs.python.org/3/reference/import.html). Full scale blogs explaining it [here](https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html) and [here](https://realpython.com/absolute-vs-relative-python-imports/). And on SO, for example [here](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Thymen Jan 15 '21 at 10:08
  • I might have misread your question, the above still provides a lot of information about the import system. But to be more precise to why you do not need `from src import flask` is because of their `__init__` file ([here](https://github.com/pallets/flask/blob/master/src/flask/__init__.py)) and their setup configurations ([here](https://github.com/pallets/flask/blob/master/setup.cfg)), which make `src` the project root. – Thymen Jan 15 '21 at 10:12
  • @Thymen , well in my `__init__.py` I have also included the main classes that I used in the test, the difference is the `setup.cfg` but I have also set the root package of my code using poetry instead. – Adam Jan 15 '21 at 10:25
  • If `src` is your project root, then you should be able to do `import myapp`, at least in my IDE (Pycharm) this would work. – Thymen Jan 15 '21 at 10:37
  • @Thymen , I think the issue is like you said in the first comment, I didn't run the `poetry install` command that puts a link to `myapp` into the `site-lib`. Thank you for the links though, they were very informative. – Adam Jan 15 '21 at 10:45

0 Answers0