Table of Contents
Motivation
Maintaining python packages for more than one python version can be a bit of a hassle
In https://creatronix.de/how-to-use-tox-to-test-your-code-on-multiple-platforms/ I’ve introduced tox.
An interesting alternative is nox(!) due to its programmatic approach
Installation
pip install nox
Example Linting
Let’s take a minimum viable example.
In our main.py we intentionally omit the newline at the end of the file.
This should result in a warning if we lint the program with flake8
if __name__ == '__main__':
print("Hello nox!")
The noxfile.py is the configuration file for nox. To use flake8 as linter we need to install it first.
After that we can run the session defined by the decorator @nox.session:
import nox
@nox.session
def lint(session):
session.install("flake8")
session.run("flake8", "example.py")
Run nox
$nox nox > Running session lint nox > Creating virtual environment (virtualenv) using python.exe in .nox\lint nox > python -m pip install flake8 nox > flake8 example.py example.py:2:24: W292 no newline at end of file nox > Command flake8 example.py failed with exit code 1 nox > Session lint failed.
Pytest
If we want to make sure that our unit tests work on a bunch of python versions we can add the required ones to the session
@nox.session(python=["3.8", "3.9", "3.10"])
def tests(session):
session.install("pytest")
session.run("pytest")
Nox creates a separate venv for every version per session and executes the tests in the specific venv.
nox > * tests-3.8: success
nox > * tests-3.9: success
nox > * tests-3.10: success
When you have multiple dependencies you can install via requirements.txt as well.
session.install("-r", "requirements.txt")