Configuration & API¶
Noxfile¶
Nox looks for configuration in a file named noxfile.py by default. You can specify
a different file using the --noxfile argument when running nox.
Defining sessions¶
Nox sessions are configured via standard Python functions that are decorated
with @nox.session. For example:
import nox
@nox.session
def tests(session):
session.run('pytest')
You can also configure sessions to run against multiple Python versions as described in Configuring a session’s virtualenv and parametrize sessions as described in parametrized sessions.
By default, all sessions will be run if no sessions are specified. You can
remove sessions from this default list by passing default=False in the
@nox.session(...) decorator. You can also specify a list of sessions to run by
default using the nox.options.sessions = [...] configuration option.
Session description¶
You can add a description to your session using a docstring. The first line will be shown when listing the sessions. For example:
import nox
@nox.session
def tests(session):
"""Run the test suite."""
session.run('pytest')
The nox --list command will show:
$ nox --list
Available sessions:
* tests -> Run the test suite.
Session name¶
By default Nox uses the decorated function’s name as the session name. This works wonderfully for the vast majority of projects, however, if you need to you can customize the session’s name by using the name argument to @nox.session. For example:
import nox
@nox.session(name="custom-name")
def a_very_long_function_name(session):
print("Hello!")
The nox --list command will show:
$ nox --list
Available sessions:
* custom-name
And you can tell nox to run the session using the custom name:
$ nox --session "custom-name"
Hello!
Configuring a session’s virtualenv¶
By default, Nox will create a new virtualenv for each session using the same interpreter that Nox uses. If you installed Nox using Python 3.6, Nox will use Python 3.6 by default for all of your sessions.
You can tell Nox to use a different Python interpreter/version by specifying the python argument (or its alias py) to @nox.session:
@nox.session(python='2.7')
def tests(session):
pass
Note
The Python binaries on Windows are found via the Python Launcher for
Windows (py). For example, Python 3.9 can be found by determining which
executable is invoked by py -3.9. If a given test needs to use the 32-bit
version of a given Python, then X.Y-32 should be used as the version.
You can also tell Nox to run your session against multiple Python interpreters. Nox will create a separate virtualenv and run the session for each interpreter you specify. For example, this session will run twice - once for Python 2.7 and once for Python 3.6:
@nox.session(python=['2.7', '3.6'])
def tests(session):
pass
When you provide a version number, Nox automatically prepends python to determine the name of the executable. However, Nox also accepts the full executable name. If you want to test using pypy, for example:
@nox.session(python=['2.7', '3.6', 'pypy-6.0'])
def tests(session):
pass
If the specified python interpreter is not found, Nox can automatically download it when --download-python is set to auto (the default) or always. never avoids the download. This requires the [pbs] extra when not using uv as a backend.
When collecting your sessions, Nox will create a separate session for each interpreter. You can see these sessions when running nox --list. For example this Noxfile:
@nox.session(python=['2.7', '3.6', '3.7', '3.8', '3.9'])
def tests(session):
pass
Will produce these sessions:
* tests-2.7
* tests-3.6
* tests-3.7
* tests-3.8
* tests-3.9
Note that this expansion happens before parameterization occurs, so you can still parametrize sessions with multiple interpreters.
If you want to disable virtualenv creation altogether, you can set python to False, or set venv_backend to "none", both are equivalent. Note that this can be done temporarily through the –no-venv commandline flag, too.
@nox.session(python=False)
def tests(session):
pass
Use of session.install() is deprecated without a virtualenv since it modifies the global Python environment. If this is what you really want, use session.run() and pip instead.
@nox.session(python=False)
def tests(session):
session.run("pip", "install", "nox")
You can also specify that the virtualenv should always be reused instead of recreated every time unless --reuse-venv=never:
@nox.session(
python=['2.7', '3.6'],
reuse_venv=True)
def tests(session):
pass
You are not limited to virtualenv, there is a selection of backends you can choose from as venv, uv, conda, mamba, micromamba, or virtualenv (default):
@nox.session(venv_backend='venv')
def tests(session):
pass
You can chain together optional backends with |, such as uv|virtualenv
or micromamba|mamba|conda, and the first available backend will be selected.
You cannot put anything after a backend that can’t be missing like venv or
virtualenv.
Finally, custom backend parameters are supported:
@nox.session(venv_params=['--no-download'])
def tests(session):
pass
If you need to check to see which backend was selected, you can access it via
session.venv_backend.
Passing arguments into sessions¶
Often it’s useful to pass arguments into your test session. Here’s a quick example that demonstrates how to use arguments to run tests against a particular file:
@nox.session
def test(session):
session.install('pytest')
if session.posargs:
test_files = session.posargs
else:
test_files = ['test_a.py', 'test_b.py']
session.run('pytest', *test_files)
Now you if you run:
nox
Then nox will run:
pytest test_a.py test_b.py
But if you run:
nox -- test_c.py
Then nox will run:
pytest test_c.py
Parametrizing sessions¶
Session arguments can be parametrized with the nox.parametrize() decorator. Here’s a typical example of parametrizing the Django version to install:
@nox.session
@nox.parametrize('django', ['1.9', '2.0'])
def tests(session, django):
session.install(f'django=={django}')
session.run('pytest')
When you run nox, it will create a two distinct sessions:
$ nox
nox > Running session tests(django='1.9')
nox > python -m pip install django==1.9
...
nox > Running session tests(django='2.0')
nox > python -m pip install django==2.0
nox.parametrize() has an interface and usage intentionally similar to pytest’s parametrize.
You can also stack the decorator to produce sessions that are a combination of the arguments, for example:
@nox.session
@nox.parametrize('django', ['1.9', '2.0'])
@nox.parametrize('database', ['postgres', 'mysql'])
def tests(session, django, database):
...
If you run nox --list, you’ll see that this generates the following set of sessions:
* tests(database='postgres', django='1.9')
* tests(database='mysql', django='1.9')
* tests(database='postgres', django='2.0')
* tests(database='mysql', django='2.0')
If you only want to run one of the parametrized sessions, see Specifying parametrized sessions.
Giving friendly names to parametrized sessions¶
The automatically generated names for parametrized sessions, such as tests(django='1.9', database='postgres'), can be long and unwieldy to work with even with using keyword filtering. You can give parametrized sessions custom IDs to help in this scenario. These two examples are equivalent:
@nox.session
@nox.parametrize('django',
['1.9', '2.0'],
ids=['old', 'new'])
def tests(session, django):
...
@nox.session
@nox.parametrize('django', [
nox.param('1.9', id='old'),
nox.param('2.0', id='new'),
])
def tests(session, django):
...
When running nox --list you’ll see their new IDs:
* tests(old)
* tests(new)
And you can run them with nox --sessions "tests(old)" and so on.
This works with stacked parameterizations as well. The IDs are combined during the combination. For example:
@nox.session
@nox.parametrize(
'django',
['1.9', '2.0'],
ids=["old", "new"])
@nox.parametrize(
'database',
['postgres', 'mysql'],
ids=["psql", "mysql"])
def tests(session, django, database):
...
Produces these sessions when running nox --list:
* tests(psql, old)
* tests(mysql, old)
* tests(psql, new)
* tests(mysql, new)
Parametrizing the session Python¶
You can use parametrization to select the Python interpreter for a session. These two examples are equivalent:
@nox.session
@nox.parametrize("python", ["3.10", "3.11", "3.12"])
def tests(session):
...
@nox.session(python=["3.10", "3.11", "3.12"])
def tests(session):
...
The first form can be useful if you need to exclude some combinations of Python versions with other parameters. For example, you may want to test against multiple versions of a dependency, but the latest version doesn’t run on older Pythons:
@nox.session
@nox.parametrize(
"python,dependency",
[
(python, dependency)
for python in ("3.10", "3.11", "3.12")
for dependency in ("1.0", "2.0")
if (python, dependency) != ("3.10", "2.0")
],
)
def tests(session, dependency):
...
The session object¶
Nox will call your session functions with an instance of the Session
class.
The pyproject.toml helpers¶
Nox provides helpers for pyproject.toml projects in the nox.project namespace.
- dependency_groups(pyproject: dict[str, Any], *groups: str) tuple[str, ...]¶
Get a list of dependencies from a
[dependency-groups]section(s).Example:
@nox.session def test(session): pyproject = nox.project.load_toml("pyproject.toml") session.install(*nox.project.dependency_groups(pyproject, "dev"))
- load_toml(filename: os.PathLike[str] | str = 'pyproject.toml', *, missing_ok: bool = False) dict[str, Any]¶
Load a toml file or a script with a PEP 723 script block.
The file must have a
.tomlextension to be considered a toml file or a.pyextension / no extension to be considered a script. Other file extensions are not valid in this function. The default is"pyproject.toml".If
missing_ok, this will return an empty dict if a script block was not found, otherwise it will raise a error.Example:
@nox.session def myscript(session): myscript_options = nox.project.load_toml("myscript.py") session.install(*myscript_options["dependencies"])
- python_versions(pyproject: dict[str, Any], *, max_version: str | None = None) list[str]¶
Read a list of supported Python versions. Without
max_version, this will read the trove classifiers (recommended). With amax_version, it will read the requires-python setting for a lower bound, and will use the value ofmax_versionas the upper bound. (Reminder: you should never set an upper bound inrequires-python).Example:
import nox PYPROJECT = nox.project.load_toml("pyproject.toml") # From classifiers PYTHON_VERSIONS = nox.project.python_versions(PYPROJECT) # Or from requires-python PYTHON_VERSIONS = nox.project.python_versions(PYPROJECT, max_version="3.13")
Modifying Nox’s behavior in the Noxfile¶
Nox has various command line arguments that can be used to modify its behavior. Some of these can also be specified in the Noxfile using nox.options. For example, if you wanted to store Nox’s virtualenvs in a different directory without needing to pass it into nox every time:
import nox
nox.options.envdir = ".cache"
@nox.session
def tests(session):
...
Or, if you wanted to provide a set of sessions that are run by default (this overrides the default= argument to sessions):
import nox
nox.options.sessions = ["lint", "tests-3.6"]
...
The following options can be specified in the Noxfile:
nox.options.envdiris equivalent to specifying –envdir.nox.options.sessionsis equivalent to specifying -s or –sessions. If set to an empty list, no sessions will be run if no sessions were given on the command line, and the list of available sessions will be shown instead.nox.options.pythonsis equivalent to specifying -p or –pythons.nox.options.keywordsis equivalent to specifying -k or –keywords.nox.options.tagsis equivalent to specifying -t or –tags.nox.options.default_venv_backendis equivalent to specifying -db or –default-venv-backend.nox.options.force_venv_backendis equivalent to specifying -fb or –force-venv-backend.nox.options.reuse_venvis equivalent to specifying –reuse-venv. Preferred over usingnox.options.reuse_existing_virtualenvs.nox.options.reuse_existing_virtualenvsis equivalent to specifying –reuse-existing-virtualenvs. You can force this off by specifying--no-reuse-existing-virtualenvsduring invocation. Alias ofnox.options.reuse_venv=yes|no.nox.options.stop_on_first_erroris equivalent to specifying –stop-on-first-error. You can force this off by specifying--no-stop-on-first-errorduring invocation.nox.options.error_on_missing_interpretersis equivalent to specifying –error-on-missing-interpreters. You can force this off by specifying--no-error-on-missing-interpretersduring invocation.nox.options.error_on_external_runis equivalent to specifying –error-on-external-run. You can force this off by specifying--no-error-on-external-runduring invocation.nox.options.download_pythonis equivalent to specifying--download-python.nox.options.reportis equivalent to specifying –report.nox.options.verboseis equivalent to specifying -v or –verbose. You can force this off by specifying--no-verboseduring invocation.
When invoking nox, any options specified on the command line take precedence over the options specified in the Noxfile. If either --sessions or --keywords is specified on the command line, both options specified in the Noxfile will be ignored.
Nox version requirements¶
Nox version requirements can be specified in your Noxfile by setting
nox.needs_version. If the Nox version does not satisfy the requirements, Nox
exits with a friendly error message. For example:
import nox
nox.needs_version = ">=2019.5.30"
@nox.session(name="test") # name argument was added in 2019.5.30
def pytest(session):
session.run("pytest")
Any of the version specifiers defined in PEP 440 can be used.
Warning
Version requirements must be specified as a string literal,
using a simple assignment to nox.needs_version at the module level. This
allows Nox to check the version without importing the Noxfile.