How to Define Nox Sessions in Python
Automate repetitive tasks like testing and linting with reusable Nox sessions.
Requires third-party packages — install first
pip install nox
Python code
18 linesimport 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
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
- Use `@nox.session(python=False)` for a session that runs on the host Python without creating a virtual env.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.