This repo documents my (evolving) ideas about "good" project structure in Python and other coding techniques useful in many projects.
-
Tests should be in
tests/and source should be insrc. This allows us to separate production code from test code, but it also causes problems withimportstatements and paths. We place our code in a package and install it as editable to address theimportproblem. To solve the path problems, see the code inconfig.pyand its usage of__file__. -
Secrets (API keys, passwords, etc.) should be protected. This is handled via
python-dotenv, which loads values from the.envfile as environment variables.
-
Create a virtual environment
python3 -m venv .venv -
Activate the virtual environment
source .venv/bin/activate -
Install required libraries
pip install -r requirements.txt -
Install source as an editable package
pip install -e . -
Create the file
.envcontaining our sensitive data (that should never go in the repo)secret=42
Once you have completed these steps you should be able to:
- Run
pytestfrom the room of the project - Run
pytestfromtests/ - Run
main.pyfrom anywhere (e.g.python src/python_structure/main.py)
requirements.txt- The list of required libraries.setup.py- The script thepipruns to install the package. The current version is bare-bones. Many other options should be set for a production system.src/python_structure/__init__.py- Establishes thepython_structuredirectory as a package. This file is empty by default.
- An argument to use the
srcfolder. This article also talks about usingtox, which is not used in this repo. - In-depth discussion of packaging, also using a
srcdirectory. Only the section, "The structure" is relevant to this repo. The rest goes further into configuring testing and continuous integration via TravisCI.