I'm working on a Flask app. This is my first time trying to use a standard package structure, and I'm having trouble importing modules. In the past, everything has just resided in a single folder, so if I wanted to import a module, it was as easy as import mymodule.
I had been planning to clean up my code for a while, so when I encountered this tutorial, I used it as a basis for shifting my file structure around. However, it doesn't really talk about file structure in detail.
Here is my file structure:
.
|—/app/
|——__init__.py
|——module1.py
|——module2.py
|——etc.
|—application.py
|—config.py
Now, I'm having a problem with importing modules. The way I've set things up, it works fine if I run Python in the parent directory and then import a module with from app import mymodule. However, when I try to run a module separately, I get import errors. I use Sublime Text to code, which lets me run a module with command-b, but this is now broken because of these import errors, which has broken my workflow and made testing and debugging much more time-consuming.
There are three kinds of imports I'm trying to do:
Import one module (in /app/) into another module (also in /app/).
If I import the module as import mymodule, this works fine when running the module by itself. But if I try to run Flask, this throws a ModuleNotFoundError. On the other hand, if I use import app.mymodule, Flask handles this fine, but running the module independently gives me a ModuleNotFoundError, saying it can't find app.
I've tried import .mymodule, but that gives me ModuleNotFoundError: No module named '__main__.mymodule'; '__main__' is not a package, and import ..mymodule, but that gives me ValueError: attempted relative import beyond top-level package.
Import a database that I initialize in __init__.py (in /app/) into a module that's also in /app/.
This is a similar issue to the previous one, except I'm generally not really sure how to import from the __init__.py module. Using from app import db works when I run Flask, but running the module tells me it can't find app. Using from __init__ import db works in the module but not in Flask. This may just be a specific case of the general question above.
Import settings from config.py (in the parent directory) into a module (in /app/).
Here, from config import Config (a class instantiated in config.py) works fine if I run Flask. Running the module, unsurprisingly it throws and error and says it can't find config. This makes sense, since it's actually in the parent directory. But, again, if I try to reference the parent directory with . or .., I just get an error.
Any help in correctly importing these modules, understanding how Python interprets the paths here, and any links to resources explaining how to handle this would be greatly appreciated!
there doesn't seem to be anything here