How to Define Nox Sessions in Python

Automate repetitive tasks like testing and linting with reusable Nox sessions.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 13 views 0 copies

Requires third-party packages — install first
pip install nox

Python code

18 lines
Python 3.9+
import nox


@nox.session(python=["3.9", "3.10"])
def tests(session):
    session.install("pytest")
    session.run("pytest")


@nox.session(python="3.9")
def lint(session):
    session.install("ruff")
    session.run("ruff", "check", ".")


if __name__ == "__main__":
    print("Nox sessions defined: tests, lint")
    print("Run with: nox -s tests")

Output

stdout
Nox sessions defined: tests, lint
Run with: nox -s tests

How it works

Nox uses decorators to define isolated virtual environments for each task. The python parameter specifies which Python versions a session runs against. session.install installs dependencies inside that virtual env, and session.run executes commands with those dependencies. Running nox from the terminal discovers and executes all sessions automatically.

Common mistakes

  • Forgetting to install required packages inside the session before running commands.
  • Using `session.env` incorrectly instead of relying on Nox's managed virtual environments.
  • Not pinning Python versions, leading to inconsistent behavior across machines.

Variations

  1. Use `@nox.session(python=False)` for a session that runs on the host Python without creating a virtual env.
  2. Pass parameters to sessions via the `@nox.parametrize` decorator to test multiple configurations.

Real-world use cases

  • Running unit tests with pytest across multiple Python versions in CI.
  • Automating code style checks and linting before merging pull requests.
  • Building and validating documentation or scripts as part of a release pipeline.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.