1

I have a flask app with the following file structure:

.env
app.py
config.py
/main_app
  __init__.py
  main.py
  /api
    api.py
    extra.py
    /models
      mod1.pkl
      mod2.pkl

In the api.py file, I have the following line:

from .extra import str2bool, load_model_pipelines, load_explainers, generate_shap_chart_data

When I call flask run from the console everything starts up fine. However, when I go to run api.py directly I get the following error message: ImportError: attempted relative import with no known parent package

If I change .extra to extra then everything works fine.

I find this puzzling. Why would it work one way when the app is run but a different way when run separately?

Jonathan Bechtel
  • 3,497
  • 4
  • 43
  • 73
  • Does this answer your question? [Relative imports in Python 3](https://stackoverflow.com/questions/16981921/relative-imports-in-python-3) – Jared Smith Jun 16 '21 at 18:12
  • Yes, but maybe not in the way I hoped :( Seems complicated – Jonathan Bechtel Jun 16 '21 at 18:22
  • Yeah, it could be better but it's really not that bad. I'd recommend using a more conventional directory structure. See [this for example](https://realpython.com/python-application-layouts/) – Jared Smith Jun 16 '21 at 18:32

0 Answers0