Setting Up
As projects grow the need to use dependencies, quality of the code and more becomes more important. This section will cover how to set up a project to use dependencies, linting and formatting.
Environment Management
With your environment you will often need 3rd party dependencies and tools to help you with your project. It’s important these dependencies are kept isolated from other projects so that they don’t interfere with each other, it also makes it easy for others to use your project.
PDM
PDM is one of several tools available to help manage your project and it works with all the required standards while being easy to use.
Using PDM
With PDM installed you can create a new project with the following command.
This will create a pyproject.toml
file that will contain all the information about your project. It will also create a pdm.lock
file that will contain all the dependencies and their versions.
Adding Dependencies
To add a dependency you can use the following command.
Or you could add it to a group (for tooling and such).
PDM Structure
Unlike having a single file for your code PDM has all your code in a src/
folder with your project folder inside of that (in this case example/
). This is to help with importing your code and to keep your project folder clean.
- pyproject.toml
Directorysrc/
Directorymypkg/
- init .py
- app.py
- view.py
Directorytests/
- test_app.py
- test_view.py …
Running code with PDM
As code sits inside of a src/
folder paths to run files will need to include that eg.
You can also use scripts to make it easier to run your code.
Other options
Linting/Formatting
To maintain the quality of code and help catch bugs before they happen it’s important to use linting and formatting tools. These tools will help you keep your code consistent and help you catch bugs before they happen.
MyPy
MyPy is a static type checker for Python, this means it will catch bugs that happen when using different types. It can catch when you accidentally use an int instead of a str and other issues.
Install MyPy
Configure MyPy
To configure MyPy you can use add the settings into your pyproject.toml
file. It is recommended to use strict mode to catch as many issues as possible.
Running MyPy
To run MyPy you can use the following command.
You can also add a script to your pyproject.toml
file to make it easier to run.
Ruff
Ruff is an all in one linting and formatting tool. It is able to check for common bugs and make sure code is formatted correctly.
Installing Ruff
Configuring Ruff
Like MyPy you can configure Ruff in your pyproject.toml
file. It has different rules that can be selected with an opinionated default below.
Running Ruff
Ruff can operate in two modes, check and fix. Check will check the code and report any issues, fix will try to fix the issues it can.
You can also add scripts to your pyproject.toml
file to make it easier to run.