Note

This documentation is for a development version. Click here for the latest stable release (v0.11.1).

Configuration options

All NengoBones configuration is done through the .nengobones.yml file. In this notebook we will demonstrate the different configuration options available and how to use them to customize behaviour for different use cases.

First we’ll define some utility functions we’ll use throughout this notebook:

[1]:
from importlib import reload
import pathlib

import nengo_bones


def write_yml(contents):
    """Create a sample .nengo.yml file from a string."""

    nengo_yml = "project_name: Example Project\n"
    nengo_yml += "pkg_name: eg_package\n"
    nengo_yml += "repo_name: eg-org/eg-package\n"
    nengo_yml += contents

    with open(".nengobones.yml", "w", encoding="utf-8") as f:
        f.write(nengo_yml)


def display_contents(filename, sections=None):
    """
    Display the contents of a file.

    The 'sections' argument filters the file to show only the
    specified sections.
    """

    with open(filename, encoding="utf-8") as f:
        data = f.readlines()

    # strip out blank lines for .sh and .yml files
    if filename.endswith(".sh") or filename.endswith(".yml"):
        data = [x for x in data if x.strip() != ""]

    if sections is None:
        display_data = data
    else:
        # pull out only the requested sections
        display_data = []
        for sec in sections:
            for i, line in enumerate(data):
                if f'"$COMMAND" == "{sec}"' in line or line.startswith(sec):
                    section_data = data[i:]
                    break
            for i, line in enumerate(section_data[1:]):
                if filename.endswith(".cfg"):
                    if line.startswith("["):
                        section_data = section_data[: i + 1]
                        break
                else:
                    if not line.startswith(" "):
                        section_data = section_data[: i + 1]
                        break
            display_data.extend(section_data)

    print("".join(display_data).rstrip("\n"))

General options

There are a few general configuration options that affect multiple templated files:

  • project_name: Natural-language name for the project (e.g., “NengoBones”).

  • pkg_name: Import name for the project (e.g., “nengo_bones”).

  • repo_name: Github organization/repository name (e.g., “nengo/nengo-bones”).

  • author: Name of project author (defaults to “Applied Brain Research”).

  • author_email: Email of project author (defaults to “info@appliedbrainresearch.com”).

  • description: A brief, one-sentence description of the project.

  • copyright_start: The year the project was first publicly available (defaults to current year).

  • copyright_end: The last year work was done on the project (defaults to current year).

  • min_python: Minimum Python version (defaults to “3.8”).

  • main_branch: Main git branch (defaults to "master").

CI scripts

NengoBones uses a continuous integration (CI) setup wherein build jobs are associated with different shell scripts, and each script defines commands to be executed at different stages during the build process. These scripts are configured through the ci_scripts section of .nengobones.yml. The basic step is to add an entry with - template: scriptname for each script template that we want to be rendered. As an example, in this section we will use the “test” template, but all the options we describe here work for any of the templated scripts.

Normally the .nengobones.yml file is a text file sitting in the root directory of the repository. For demonstration purposes, in this notebook we will be generating different config files on-the-fly using the utility functions from above.

[2]:
nengobones_yml = """
ci_scripts:
    - template: test
"""
# create .nengobones.yml file
write_yml(nengobones_yml)
# call the bones generate script
!bones generate ci-scripts
# display the contents of the generated file
display_contents("test.sh")
#!/usr/bin/env bash
# Automatically generated by nengo-bones, do not edit this file directly
NAME=$0
COMMAND=$1
STATUS=0  # used to exit with non-zero status if any command fails
# shellcheck disable=SC2034
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
export JOB_NUMBER="$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
if [[ -n "$JOB_SUFFIX" ]]; then
    export JOB_NUMBER="$JOB_NUMBER-$JOB_SUFFIX"
fi
export GIT_BRANCH="${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}}"
if [[ "$GITHUB_REF_TYPE" == "tag" ]]; then
    export GIT_TAG="$GIT_BRANCH"
fi
exe() {
    echo "\$ $*";
    # remove empty spaces from args
    args=( "$@" )
    for i in "${!args[@]}"; do
      [ -n "${args[$i]}" ] || unset "args[$i]"
    done
    "${args[@]}" || { echo -e "\033[1;31mCOMMAND '${args[0]}' FAILED\033[0m"; STATUS=1; }
}
if [[ ! -e eg_package ]]; then
    echo "Run this script from the root directory of this repository"
    exit 1
fi
if [[ "$COMMAND" == "install" ]]; then
    :
    exe pip install "pytest>=7.0.0"
    exe pip install "pytest-xdist>=3.2.0"
    exe pip install -e ".[tests]"
elif [[ "$COMMAND" == "script" ]]; then
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS
elif [[ "$COMMAND" == "after_success" ]]; then
    :
elif [[ "$COMMAND" == "after_failure" ]]; then
    :
elif [[ "$COMMAND" == "after_script" ]]; then
    :
elif [[ -z "$COMMAND" ]]; then
    echo "$NAME requires a command like 'install' or 'script'"
else
    echo "$NAME does not define $COMMAND"
fi
exit "$STATUS"

There is a lot of information in that file that we don’t really need to worry about (that’s the whole point of NengoBones, to take care of those details for us). We can see that the overall structure is made up of behaviour defined for different build stages (e.g. “install”, “before_script”, etc.). In most cases all the important action happens in the “install” and “script” stages:

[3]:
display_contents("test.sh", sections=["install", "script"])
if [[ "$COMMAND" == "install" ]]; then
    :
    exe pip install "pytest>=7.0.0"
    exe pip install "pytest-xdist>=3.2.0"
    exe pip install -e ".[tests]"
elif [[ "$COMMAND" == "script" ]]; then
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS

In the “install” stage we install any of the package requirements needed to run the script. In this case we can see we’re installing pytest, pytest-xdist, and the current package (including any optional dependencies defined in the [tests] extra_requires directive).

If we need to add extra packages to this default installation, that can be done with the pip_install configuration option:

[4]:
nengobones_yml = """
ci_scripts:
    - template: test
      pip_install:
          - an-extra-pip-package
"""
write_yml(nengobones_yml)
!bones generate ci-scripts
display_contents("test.sh", sections=["install"])
if [[ "$COMMAND" == "install" ]]; then
    exe pip install "an-extra-pip-package"
    exe pip install "pytest>=7.0.0"
    exe pip install "pytest-xdist>=3.2.0"
    exe pip install -e ".[tests]"

Note that requirements should generally be added to the package requirements defined in setup.py (in which case they would be automatically installed in the pip install -e ".[tests]" step). That way anyone can easily install the necessary packages and run the tests without having to go through the CI scripts. The pip_install option is only necessary if that isn’t feasible for some reason.

The “script” stage is where the main work of the script is done. In the case of the “test” script, this means calling pytest to run the test suite:

[5]:
display_contents("test.sh", sections=["script"])
elif [[ "$COMMAND" == "script" ]]; then
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS

As with the “install” stage, the “script” stage can also be customized if we want to add extra commands, either before or after the main script body:

[6]:
nengobones_yml = """
ci_scripts:
    - template: test
      pre_commands:
          - echo "this command will run at the beginning"
      post_commands:
          - echo "this command will run at the end"
"""
write_yml(nengobones_yml)
!bones generate ci-scripts
display_contents("test.sh", sections=["script"])
elif [[ "$COMMAND" == "script" ]]; then
    exe echo "this command will run at the beginning"
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS
    exe echo "this command will run at the end"

We can also use the same template multiple times, passing different options to generate different output scripts. In this case we need to use the output_name config option to distinguish different rendered scripts:

[7]:
nengobones_yml = """
ci_scripts:
    - template: test
      pre_commands:
          - echo "this is test"
    - template: test
      output_name: test2
      pre_commands:
          - echo "this is test2"
"""
write_yml(nengobones_yml)
!bones generate ci-scripts
print("Contents of test.sh")
print("-------------------")
display_contents("test.sh", sections=["script"])
print("\nContents of test2.sh")
print("--------------------")
display_contents("test2.sh", sections=["script"])
Contents of test.sh
-------------------
elif [[ "$COMMAND" == "script" ]]; then
    exe echo "this is test"
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS

Contents of test2.sh
--------------------
elif [[ "$COMMAND" == "script" ]]; then
    exe echo "this is test2"
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS

Test script options

The “test” script has some configuration options specific to that script. First, we can collect coverage information while tests are running by setting coverage: true:

[8]:
nengobones_yml = """
ci_scripts:
    - template: test
      coverage: true
"""
write_yml(nengobones_yml)
!bones generate ci-scripts
display_contents("test.sh", sections=["install", "script", "after_script"])
if [[ "$COMMAND" == "install" ]]; then
    :
    exe pip install "pytest>=7.0.0"
    exe pip install "pytest-xdist>=3.2.0"
    exe pip install "pytest-cov>=4.0.0"
    exe pip install -e ".[tests]"
elif [[ "$COMMAND" == "script" ]]; then
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 --cov=eg_package --cov-report=term-missing $TEST_ARGS
elif [[ "$COMMAND" == "after_script" ]]; then
    :

Note that the script is now installing extra packages, adding extra arguments to pytest, and uploading the results to Codecov at the end.

Nengo backends also often want to run the core Nengo tests in addition to their own test suite. This can be accomplished by setting nengo_tests: true:

[9]:
nengobones_yml = """
ci_scripts:
    - template: test
      nengo_tests: true
"""
write_yml(nengobones_yml)
!bones generate ci-scripts
display_contents("test.sh", sections=["script"])
elif [[ "$COMMAND" == "script" ]]; then
    # shellcheck disable=SC2086
    exe pytest eg_package -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS
    # shellcheck disable=SC2086
    exe pytest --pyargs nengo -v -n 3 --dist worksteal --color=yes --durations 20 $TEST_ARGS

LICENSE.rst config

A license file can be automatically generated by NengoBones. Currently the Nengo License and MIT License are supported as base templates (specified by the type tag).

[10]:
nengobones_yml = """
license_rst:
    type: nengo
"""
write_yml(nengobones_yml)
!bones generate license-rst
display_contents("LICENSE.rst")
.. Automatically generated by nengo-bones, do not edit this file directly

***********************
Example Project license
***********************

Copyright (c) 2024-2024 Applied Brain Research

All information contained herein is and remains the property of
Applied Brain Research. The intellectual and technical concepts contained
herein are proprietary to Applied Brain Research and may be covered by U.S.
and Foreign Patents, patents in process, and are protected by trade secret
or copyright law. Dissemination of this information or reproduction of this
material is strictly forbidden unless prior written permission is obtained
from Applied Brain Research. Access to the source code contained herein is
hereby forbidden to anyone except current Applied Brain Research employees,
contractors or other outside parties that have executed Confidentiality
and/or Non-disclosure agreements explicitly covering such access.

The copyright notice above does not evidence any actual or intended
publication or disclosure of this source code, which includes information
that is confidential and/or proprietary, and is a trade secret, of
Applied Brain Research. ANY REPRODUCTION, MODIFICATION, DISTRIBUTION,
PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS
SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF APPLIED BRAIN RESEARCH
IS STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE LAWS AND
INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE
CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS
TO REPRODUCE, DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE,
USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.

Note that this template uses several of the general options described above (project_name, author, author_email, copyright_start, copyright_end).

[11]:
nengobones_yml = """
author: A Different Author
copyright_start: 1900
license_rst:
    type: mit
"""
write_yml(nengobones_yml)
!bones generate license-rst
display_contents("LICENSE.rst")
.. Automatically generated by nengo-bones, do not edit this file directly

***********************
Example Project license
***********************

Copyright (c) 1900-2024 A Different Author

All information contained herein is and remains the property of
Applied Brain Research. The intellectual and technical concepts contained
herein are proprietary to Applied Brain Research and may be covered by U.S.
and Foreign Patents, patents in process, and are protected by trade secret
or copyright law. Dissemination of this information or reproduction of this
material is strictly forbidden unless prior written permission is obtained
from Applied Brain Research. Access to the source code contained herein is
hereby forbidden to anyone except current Applied Brain Research employees,
contractors or other outside parties that have executed Confidentiality
and/or Non-disclosure agreements explicitly covering such access.

The copyright notice above does not evidence any actual or intended
publication or disclosure of this source code, which includes information
that is confidential and/or proprietary, and is a trade secret, of
Applied Brain Research. ANY REPRODUCTION, MODIFICATION, DISTRIBUTION,
PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS
SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF APPLIED BRAIN RESEARCH
IS STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE LAWS AND
INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE
CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS
TO REPRODUCE, DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE,
USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.

CONTRIBUTING.rst config

The CONTRIBUTING.rst file instructs potential contributors on how to contribute to the project. It has no configuration options, although it makes use of some of the general options (project_name, repo_name).

[12]:
nengobones_yml = """
contributing_rst: {}
"""
write_yml(nengobones_yml)

!bones generate contributing-rst
display_contents("CONTRIBUTING.rst")
.. Automatically generated by nengo-bones, do not edit this file directly

*******************************
Contributing to Example Project
*******************************

Issues and pull requests are always welcome!
We appreciate help from the community to make Example Project better.

Filing issues
=============

If you find a bug in Example Project,
or think that a certain feature is missing,
please consider
`filing an issue <https://github.com/eg-org/eg-package/issues>`_!
Please search the currently open issues first
to see if your bug or feature request already exists.
If so, feel free to add a comment to the issue
so that we know that multiple people are affected.

Making pull requests
====================

If you want to fix a bug or add a feature to Example Project,
we welcome pull requests.
Ensure that you fill out all sections of the pull request template,
deleting the comments as you go.

Contributor agreement
=====================

We require that all contributions be covered under
our contributor assignment agreement. Please see
`the agreement <https://www.nengo.ai/caa/>`_
for instructions on how to sign.

More details
============

For more details on how to contribute to Nengo,
please see the `developer guide <https://www.nengo.ai/contributing/>`_.

CONTRIBUTORS.rst config

The CONTRIBUTORS.rst file links to the contributor list for the project. It always provides the Github contributors link, which lists all people who have committed to the project.

[13]:
nengobones_yml = """
contributors_rst: {}
"""
write_yml(nengobones_yml)

!bones generate contributors-rst
display_contents("CONTRIBUTORS.rst")
.. Automatically generated by nengo-bones, do not edit this file directly

****************************
Example Project contributors
****************************

See https://github.com/eg-org/eg-package/graphs/contributors
for a list of the people who have committed to Example Project.
Thank you for your contributions!

The nengo_list flag includes the full list of Nengo ecosystem contributors. It defaults to True if the license type is the “nengo” license, and False otherwise.

[14]:
nengobones_yml = """
contributors_rst:
    nengo_list: True
"""
write_yml(nengobones_yml)

!bones generate contributors-rst
display_contents("CONTRIBUTORS.rst")
.. Automatically generated by nengo-bones, do not edit this file directly

****************************
Example Project contributors
****************************

See https://github.com/eg-org/eg-package/graphs/contributors
for a list of the people who have committed to Example Project.
Thank you for your contributions!

MANIFEST.in config

The MANIFEST.in template defines some standard rules for the project manifest:

[15]:
nengobones_yml = """
manifest_in: {}
"""
write_yml(nengobones_yml)

!bones generate manifest-in
display_contents("MANIFEST.in")
# Automatically generated by nengo-bones, do not edit this file directly

global-include *.py
global-include *.sh
global-include *.template
include *.rst

# Include files for CI and recreating the source dist
include *.yml
include *.yaml
include *.toml
include MANIFEST.in
include .gitlint
include .pylintrc

# Directories to include
graft docs

# Subdirectories to exclude, if they exist
prune docs/_build
prune dist
prune .git
prune .github
prune .tox
prune .eggs
prune .ci
prune bones-scripts

# Exclude auto-generated files
recursive-exclude docs *.py

# Patterns to exclude from any directory
global-exclude *.ipynb_checkpoints*
global-exclude *-checkpoint.ipynb

# Exclude all bytecode
global-exclude *.pyc *.pyo *.pyd

Arbitrary additions can be made to this list by setting configuration options with the appropriate MANIFEST rule heading:

[16]:
nengobones_yml = """
manifest_in:
    global-include:
        - global_include_pattern0
        - global_include_pattern1
    graft:
        - graft_pattern0
"""
write_yml(nengobones_yml)

!bones generate manifest-in
display_contents("MANIFEST.in")
# Automatically generated by nengo-bones, do not edit this file directly

global-include *.py
global-include *.sh
global-include *.template
include *.rst

# Include files for CI and recreating the source dist
include *.yml
include *.yaml
include *.toml
include MANIFEST.in
include .gitlint
include .pylintrc

# Directories to include
graft docs

# Subdirectories to exclude, if they exist
prune docs/_build
prune dist
prune .git
prune .github
prune .tox
prune .eggs
prune .ci
prune bones-scripts

# Exclude auto-generated files
recursive-exclude docs *.py

# Patterns to exclude from any directory
global-exclude *.ipynb_checkpoints*
global-exclude *-checkpoint.ipynb

# Exclude all bytecode
global-exclude *.pyc *.pyo *.pyd

# Repo-specific files
global-include global_include_pattern0
global-include global_include_pattern1
graft graft_pattern0

setup.cfg config

The setup.cfg file contains configuration options for a number of different tools. In addition to the specific options defined below, the setup.cfg template makes use of the general pkg_name option to set various file/path names.

[17]:
nengobones_yml = """
setup_cfg: {}
"""
write_yml(nengobones_yml)

!bones generate setup-cfg
display_contents("setup.cfg")
# Automatically generated by nengo-bones, do not edit this file directly

[build_sphinx]
source-dir = docs
build-dir = docs/_build
all_files = 1

[coverage:run]
source = ./
relative_files = True

[coverage:report]
# Regexes for lines to exclude from consideration
exclude_lines =
    # Have to re-enable the standard pragma
    # place ``# pragma: no cover`` at the end of a line to ignore it
    pragma: no cover

    # Don't complain if tests don't hit defensive assertion code:
    raise NotImplementedError

    # `pass` is just a placeholder, fine if it's not covered
    ^[ \t]*pass$


# Patterns for files to exclude from reporting
omit =
    */tests/test*

[flake8]
exclude =
    __init__.py
ignore =
    E123
    E133
    E203
    E226
    E241
    E242
    E501
    E731
    F401
    W503
max-complexity = 10
max-line-length = 88

[tool:pytest]
norecursedirs =
    .*
    *.egg
    build
    dist
    docs
xfail_strict = False

[pylint]

[pylint.messages]
disable =
    arguments-differ,
    assignment-from-no-return,
    attribute-defined-outside-init,
    blacklisted-name,
    comparison-with-callable,
    duplicate-code,
    fixme,
    import-error,
    invalid-name,
    invalid-sequence-index,
    len-as-condition,
    literal-comparison,
    no-else-raise,
    no-else-return,
    no-member,
    no-name-in-module,
    not-an-iterable,
    not-context-manager,
    protected-access,
    redefined-builtin,
    stop-iteration-return,
    too-few-public-methods,
    too-many-arguments,
    too-many-branches,
    too-many-instance-attributes,
    too-many-lines,
    too-many-locals,
    too-many-return-statements,
    too-many-statements,
    unexpected-keyword-arg,
    unidiomatic-typecheck,
    unsubscriptable-object,
    unsupported-assignment-operation,
    unused-argument,

[pylint.imports]
known-third-party =
    matplotlib,
    nengo,
    numpy,
    pytest,

[pylint.format]
max-line-length = 88

[pylint.classes]
valid-metaclass-classmethod-first-arg = metacls

[pylint.reports]
reports = no
score = no

[codespell]
skip = ./build,*/_build,*-checkpoint.ipynb,./.eggs,./*.egg-info,./.git,*/_vendor,./.mypy_cache,

Each of the tools configured by setup.cfg has its own subheading in the .nengobones.yml setup_cfg section.

coverage has two options:

  • exclude_lines: a list of regex expressions that will be ignored in code coverage reports

  • omit_files: a list of filename patterns that will be ignored

Note that some defaults are already specified in both cases, and any options passed are in addition to those defaults.

[18]:
nengobones_yml = """
setup_cfg:
    coverage:
        exclude_lines:
            # Ignore all loops
            - for *
            - while *
        omit_files:
            # Ignore all files in subdirectory
            - subdir/*
"""
write_yml(nengobones_yml)

!bones generate setup-cfg
display_contents("setup.cfg", sections=["[coverage:run]", "[coverage:report]"])
[coverage:run]
source = ./
relative_files = True

[coverage:report]
# Regexes for lines to exclude from consideration
exclude_lines =
    # Have to re-enable the standard pragma
    # place ``# pragma: no cover`` at the end of a line to ignore it
    pragma: no cover

    # Don't complain if tests don't hit defensive assertion code:
    raise NotImplementedError

    # `pass` is just a placeholder, fine if it's not covered
    ^[ \t]*pass$

    for *
    while *

# Patterns for files to exclude from reporting
omit =
    */tests/test*
    subdir/*

The flake8 section has two options:

  • exclude: a list of filename patterns to be ignored

  • ignore: a list of rules to be ignored; see https://www.flake8rules.com/ for a full list.

[19]:
nengobones_yml = """
setup_cfg:
    flake8:
        exclude:
            - subdir/*
        ignore:
            - E101
            - E111
"""
write_yml(nengobones_yml)

!bones generate setup-cfg
display_contents("setup.cfg", sections=["[flake8]"])
[flake8]
exclude =
    __init__.py
    subdir/*
ignore =
    E123
    E133
    E203
    E226
    E241
    E242
    E501
    E731
    F401
    W503
    E101
    E111
max-complexity = 10
max-line-length = 88

The pytest section has the following general options:

  • addopts: A list of command line options to pass to any pytest invocation (defaults to -p nengo.tests.options, which will add the pytest command line options from Nengo core).

  • xfail_strict: If True, xpass will be treated as a failure (defaults to False).

  • norecursedirs: A list of directory name patterns that should not be searched for test files.

  • markers: Descriptions for any custom markers that can be applied to test functions.

  • filterwarnings: Controls how warnings will be handled (see https://docs.python.org/3/library/warnings.html#warning-filter for a description of how to write warning filters).

And the following options for Pytest plugins.

pytest-allclose:

  • allclose_tolerances: A list of test name patterns and associated tolerance values.

pytest_nengo:

  • nengo_neurons: Specifies which neuron types to test.

  • nengo_simulator: Specifies the Nengo backend to test.

  • nengo_simloader: Specifies a function that returns the Nengo backend to test.

  • nengo_test_unsupported: Marks which core tests are not expected to pass.

pytest-plt:

  • plt_dirname: A directory name to store plots.

  • plt_filename_drop: A list of regular expressions to drop parts of plot filenames.

pytest-rng:

  • rng_salt: A salt value to modify seeds.

[20]:
nengobones_yml = r"""
setup_cfg:
    pytest:
        addopts:
            - -p nengo.tests.options
            - --colors=yes
        xfail_strict: true
        norecursedirs:
            - subdir0
            - subdir1
        markers:
            marker0: description of marker0
            marker1: description of marker1
        filterwarnings:
            - ignore::UserWarning
            - error::ResourceWarning
        nengo_test_unsupported:
            test_ensemble.py::test_encoders*:
                This backend does not support encoders
        allclose_tolerances:
            - "test_ensemble.py::test_encoders* atol=0.01 rtol=0.05  # comment"
        plt_dirname: nengo.plots
        plt_filename_drop:
            - "^nengo\\."
        rng_salt: v1.0.0
"""
write_yml(nengobones_yml)

!bones generate setup-cfg
display_contents("setup.cfg", sections=["[tool:pytest]"])
[tool:pytest]
addopts = -p nengo.tests.options --colors=yes
norecursedirs =
    .*
    *.egg
    build
    dist
    docs
    subdir0
    subdir1
markers =
    marker0: description of marker0
    marker1: description of marker1
xfail_strict = True
filterwarnings =
    ignore::UserWarning
    error::ResourceWarning
nengo_test_unsupported =
    test_ensemble.py::test_encoders*
        "This backend does not support encoders"
allclose_tolerances =
    test_ensemble.py::test_encoders* atol=0.01 rtol=0.05  # comment
plt_dirname = nengo.plots
plt_filename_drop =
    ^nengo\.
rng_salt = v1.0.0

The pylint section has three options:

  • ignore: A list of filename patterns to ignore.

  • disable: A list of pylint rules to ignore (see https://github.com/janjur/readable-pylint-messages). Note that a number of rules are already disabled by default, and any rules specified here will be in addition to those.

  • known-third-party: A list of third party modules (sometimes pylint will fail to detect that a module is third-party, and then complain about the import order).

[21]:
nengobones_yml = """
setup_cfg:
    pylint:
        ignore:
            - __init__.py
        disable:
            - empty-docstring
            - unneeded-not
        known_third_party:
            - scipy
"""
write_yml(nengobones_yml)

!bones generate setup-cfg
display_contents(
    "setup.cfg", sections=["[pylint]", "[pylint.messages]", "[pylint.imports]"]
)
[pylint]
ignore =
    __init__.py,

[pylint.messages]
disable =
    arguments-differ,
    assignment-from-no-return,
    attribute-defined-outside-init,
    blacklisted-name,
    comparison-with-callable,
    duplicate-code,
    fixme,
    import-error,
    invalid-name,
    invalid-sequence-index,
    len-as-condition,
    literal-comparison,
    no-else-raise,
    no-else-return,
    no-member,
    no-name-in-module,
    not-an-iterable,
    not-context-manager,
    protected-access,
    redefined-builtin,
    stop-iteration-return,
    too-few-public-methods,
    too-many-arguments,
    too-many-branches,
    too-many-instance-attributes,
    too-many-lines,
    too-many-locals,
    too-many-return-statements,
    too-many-statements,
    unexpected-keyword-arg,
    unidiomatic-typecheck,
    unsubscriptable-object,
    unsupported-assignment-operation,
    unused-argument,
    empty-docstring,
    unneeded-not,

[pylint.imports]
known-third-party =
    matplotlib,
    nengo,
    numpy,
    pytest,
    scipy,

The codespell section has two options:

  • skip: A list of files to ignore.

  • ignore_words: A list of strings that we want to omit from spellchecking.

[22]:
nengobones_yml = """
setup_cfg:
    codespell:
        skip:
            - filewitherrors.py
        ignore_words:
            - notaword
            - stillnotaword
"""
write_yml(nengobones_yml)

!bones generate setup-cfg
display_contents("setup.cfg", sections=["[codespell]"])
[codespell]
skip = ./build,*/_build,*-checkpoint.ipynb,./.eggs,./*.egg-info,./.git,*/_vendor,./.mypy_cache,filewitherrors.py
ignore-words-list = notaword,stillnotaword

setup.py config

The setup.py template has a number of configuration options, and also makes use of some of the general config settings (pkg_name, author, author_email, description).

[23]:
nengobones_yml = """
setup_py: {}
"""
write_yml(nengobones_yml)

!bones generate setup-py
display_contents("setup.py")
# Automatically generated by nengo-bones, do not edit this file directly

import io
import pathlib
import runpy

try:
    from setuptools import find_packages, setup
except ImportError:
    raise ImportError(
        "'setuptools' is required but not installed. To install it, "
        "follow the instructions at "
        "https://pip.pypa.io/en/stable/installing/#installing-with-get-pip-py"
    )


def read(*filenames, **kwargs):
    encoding = kwargs.get("encoding", "utf-8")
    sep = kwargs.get("sep", "\n")
    buf = []
    for filename in filenames:
        with io.open(filename, encoding=encoding) as f:
            buf.append(f.read())
    return sep.join(buf)


root = pathlib.Path(__file__).parent
version = runpy.run_path(str(root / "eg_package" / "version.py"))["version"]

install_req = []
docs_req = []
optional_req = []
tests_req = []

setup(
    name="eg-package",
    version=version,
    author="Applied Brain Research",
    author_email="[email protected]",
    packages=find_packages(),
    url="https://www.nengo.ai/eg-package",
    include_package_data=False,
    license="Proprietary",
    description="",
    long_description=read("README.rst", "CHANGES.rst"),
    zip_safe=False,
    install_requires=install_req,
    extras_require={
        "all": docs_req + optional_req + tests_req,
        "docs": docs_req,
        "optional": optional_req,
        "tests": tests_req,
    },
    python_requires=">=3.8",
    classifiers=[
        "License :: Other/Proprietary License",
    ],
)

Package dependencies are defined in the install_req (the main dependencies required to use the package), optional_req (dependencies that aren’t necessary but activate extra functionality), docs_req (requirements for building the documentation), and tests_req (requirements for running the test suite) fields.

[24]:
nengobones_yml = """
setup_py:
    install_req:
        - package0
        - package1
    optional_req:
        - package2
        - package3
    docs_req:
        - package4
        - package5
    tests_req:
        - package6
        - package7
"""
write_yml(nengobones_yml)

!bones generate setup-py
display_contents(
    "setup.py", sections=["install_req", "optional_req", "docs_req", "tests_req"]
)
install_req = [
    "package0",
    "package1",
optional_req = [
    "package2",
    "package3",
docs_req = [
    "package4",
    "package5",
tests_req = [
    "package6",
    "package7",

There are a number of options that will be passed to the setup function:

  • url: A link to the project’s homepage (defaults to nengo.ai/my-package).

  • python_requires: Python version requirement for this package (defaults to '>={{ min_python }}').

  • include_package_data: Whether or not to include files listed in MANIFEST.in in the installation (defaults to False).

  • package_data: Mapping of extra data files to include in installation (not specified by MANIFEST.in).

  • classifiers: List of Trove classifiers.

  • entry_points: Dictionary of entry points to make available.

See the distutils and setuptools documentation for more details on these options.

[25]:
nengobones_yml = """
setup_py:
    url: https://github.com/org/my-package
    python_requires: ">=3.4,<3.9"
    include_package_data: true
    package_data:
        pkg:
            - file0
            - file1
    classifiers:
        - "Development Status :: 3 - Alpha"
        - "Framework :: Nengo"
    entry_points:
        nengo.backends:
            - my_backend = my_backend:Simulator
        console_scripts:
            - my-script = my_project.file:function
"""
write_yml(nengobones_yml)

!bones generate setup-py
display_contents("setup.py", sections=["setup"])
setup(
    name="eg-package",
    version=version,
    author="Applied Brain Research",
    author_email="[email protected]",
    packages=find_packages(),
    url="https://github.com/org/my-package",
    include_package_data=True,
    license="Proprietary",
    description="",
    long_description=read("README.rst", "CHANGES.rst"),
    zip_safe=False,
    install_requires=install_req,
    extras_require={
        "all": docs_req + optional_req + tests_req,
        "docs": docs_req,
        "optional": optional_req,
        "tests": tests_req,
    },
    python_requires=">=3.4,<3.9",
    package_data={
        "pkg": [
            "file0",
            "file1",
        ],
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Framework :: Nengo",
        "License :: Other/Proprietary License",
    ],
    entry_points={
        "nengo.backends": [
            "my_backend = my_backend:Simulator",
        ],
        "console_scripts": [
            "my-script = my_project.file:function",
        ],
    },

docs/conf.py config

The docs/conf.py file contains settings controlling Sphinx documentation. It makes use of several general configuration options (pkg_name, project_name, author, copyright_start, copyright_end).

[26]:
nengobones_yml = """
docs_conf_py: {}
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py")
# -*- coding: utf-8 -*-
#
# Automatically generated by nengo-bones, do not edit this file directly

import pathlib

import eg_package

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.doctest",
    "sphinx.ext.githubpages",
    "sphinx.ext.intersphinx",
    "sphinx.ext.mathjax",
    "sphinx.ext.todo",
    "nbsphinx",
    "nengo_sphinx_theme",
    "nengo_sphinx_theme.ext.sourcelinks",
    "notfound.extension",
    "numpydoc",
]

# -- sphinx.ext.autodoc
autoclass_content = "both"  # class and __init__ docstrings are concatenated
autodoc_default_options = {"members": None}
autodoc_member_order = "bysource"  # default is alphabetical

# -- sphinx.ext.doctest
doctest_global_setup = """
import eg_package
"""

# -- sphinx.ext.intersphinx
intersphinx_mapping = {
    "nengo": ("https://www.nengo.ai/nengo/", None),
    "numpy": ("https://numpy.org/doc/stable", None),
    "python": ("https://docs.python.org/3", None),
}

# -- sphinx.ext.todo
todo_include_todos = True

# -- nbsphinx
nbsphinx_timeout = -1

# -- notfound.extension
notfound_template = "404.html"
notfound_urls_prefix = "/eg-package/"

# -- numpydoc config
numpydoc_show_class_members = False

# -- nengo_sphinx_theme.ext.sourcelinks
sourcelinks_module = "eg_package"
sourcelinks_url = "https://github.com/eg-org/eg-package"

# -- sphinx
nitpicky = True
exclude_patterns = [
    "_build",
    "**/.ipynb_checkpoints",
]
linkcheck_timeout = 30
source_suffix = ".rst"
source_encoding = "utf-8"
master_doc = "index"
linkcheck_ignore = [r"http://localhost:\d+"]
linkcheck_anchors = True
default_role = "py:obj"
pygments_style = "sphinx"
user_agent = "eg_package"

project = "Example Project"
authors = "Applied Brain Research"
copyright = "2024-2024 Applied Brain Research"
version = ".".join(eg_package.__version__.split(".")[:2])  # Short X.Y version
release = eg_package.__version__  # Full version, with tags

# -- HTML output
templates_path = ["_templates"]
html_static_path = ["_static"]
html_theme = "nengo_sphinx_theme"
html_title = f"Example Project {release} docs"
htmlhelp_basename = "Example Project"
html_last_updated_fmt = ""  # Default output format (suppressed)
html_show_sphinx = False
html_favicon = str(pathlib.Path("_static", "favicon.ico"))
html_theme_options = {
    "nengo_logo": "general-full-light.svg",
    "nengo_logo_color": "#a8acaf",
    "analytics": """
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-GT8XEDLTMJ"></script>
        <script>
         window.dataLayer = window.dataLayer || [];
         function gtag(){dataLayer.push(arguments);}
         gtag('js', new Date());
         gtag('config', 'G-GT8XEDLTMJ');
        </script>
        <!-- End Google tag (gtag.js) -->
        <!-- Matomo -->
        <script>
         var _paq = window._paq = window._paq || [];
         _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
         _paq.push(["setCookieDomain", "*.appliedbrainresearch.com"]);
         _paq.push(["setDomains", ["*.appliedbrainresearch.com","*.edge.nengo.ai","*.forum.nengo.ai","*.nengo.ai"]]);
         _paq.push(["enableCrossDomainLinking"]);
         _paq.push(["setDoNotTrack", true]);
         _paq.push(['trackPageView']);
         _paq.push(['enableLinkTracking']);
         (function() {
           var u="https://appliedbrainresearch.matomo.cloud/";
           _paq.push(['setTrackerUrl', u+'matomo.php']);
           _paq.push(['setSiteId', '3']);
           var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
           g.async=true; g.src='//cdn.matomo.cloud/appliedbrainresearch.matomo.cloud/matomo.js'; s.parentNode.insertBefore(g,s);
         })();
        </script>
        <!-- End Matomo Code -->
    """,
}

Extra Sphinx extensions can be added by setting the extensions config option:

[27]:
nengobones_yml = """
docs_conf_py:
    extensions:
        - a_sphinx_extension
        - another_sphinx_extension
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["extensions"])
extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.doctest",
    "sphinx.ext.githubpages",
    "sphinx.ext.intersphinx",
    "sphinx.ext.mathjax",
    "sphinx.ext.todo",
    "nbsphinx",
    "nengo_sphinx_theme",
    "nengo_sphinx_theme.ext.sourcelinks",
    "notfound.extension",
    "numpydoc",
    "a_sphinx_extension",
    "another_sphinx_extension",

Extra intersphinx mappings (for linking to documentation in other projects) can be added by setting the intersphinx_mapping config option, which is a mapping from package names to documentation URLs (the linked documentations must also be generated by Sphinx).

[28]:
nengobones_yml = """
docs_conf_py:
    intersphinx_mapping:
        scipy: https://docs.scipy.org/doc/scipy/reference
        sklearn: https://scikit-learn.org/dev
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["intersphinx_mapping"])
intersphinx_mapping = {
    "nengo": ("https://www.nengo.ai/nengo/", None),
    "numpy": ("https://numpy.org/doc/stable", None),
    "python": ("https://docs.python.org/3", None),
    "scipy": ("https://docs.scipy.org/doc/scipy/reference", None),
    "sklearn": ("https://scikit-learn.org/dev", None),

The exclude_patterns config option is a list of file/directory name patterns that should not be included in the documentation rendering.

[29]:
nengobones_yml = """
docs_conf_py:
    exclude_patterns:
        - a-file.py
        - subdir
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["exclude_patterns"])
exclude_patterns = [
    "_build",
    "**/.ipynb_checkpoints",
    "a-file.py",
    "subdir",

The nengo_logo config option contains the name of the logo image that will be rendered in the sidebar. The image filename refers to the nengo/design assets. The default is general-full-light.svg, which refers to this logo.

[30]:
nengobones_yml = """
docs_conf_py:
    nengo_logo: nengo-dl-full-light.svg
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["html_theme_options"])
html_theme_options = {
    "nengo_logo": "nengo-dl-full-light.svg",
    "nengo_logo_color": "#a8acaf",
    "analytics": """
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-GT8XEDLTMJ"></script>
        <script>
         window.dataLayer = window.dataLayer || [];
         function gtag(){dataLayer.push(arguments);}
         gtag('js', new Date());
         gtag('config', 'G-GT8XEDLTMJ');
        </script>
        <!-- End Google tag (gtag.js) -->
        <!-- Matomo -->
        <script>
         var _paq = window._paq = window._paq || [];
         _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
         _paq.push(["setCookieDomain", "*.appliedbrainresearch.com"]);
         _paq.push(["setDomains", ["*.appliedbrainresearch.com","*.edge.nengo.ai","*.forum.nengo.ai","*.nengo.ai"]]);
         _paq.push(["enableCrossDomainLinking"]);
         _paq.push(["setDoNotTrack", true]);
         _paq.push(['trackPageView']);
         _paq.push(['enableLinkTracking']);
         (function() {
           var u="https://appliedbrainresearch.matomo.cloud/";
           _paq.push(['setTrackerUrl', u+'matomo.php']);
           _paq.push(['setSiteId', '3']);
           var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
           g.async=true; g.src='//cdn.matomo.cloud/appliedbrainresearch.matomo.cloud/matomo.js'; s.parentNode.insertBefore(g,s);
         })();
        </script>
        <!-- End Matomo Code -->
    """,

The nengo_logo_color config option contains the primary color associated with the logo. This information should also be present in the nengo/design repository. The default is #a8acaf, which is a neutral gray appropriate for projects without a primary color.

Note that because # prefixes comments in YAML, you must enclose hex color entries in single or double quotes.

[31]:
nengobones_yml = """
docs_conf_py:
    nengo_logo_color: '#abcdef'
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["html_theme_options"])
html_theme_options = {
    "nengo_logo": "general-full-light.svg",
    "nengo_logo_color": "#abcdef",
    "analytics": """
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-GT8XEDLTMJ"></script>
        <script>
         window.dataLayer = window.dataLayer || [];
         function gtag(){dataLayer.push(arguments);}
         gtag('js', new Date());
         gtag('config', 'G-GT8XEDLTMJ');
        </script>
        <!-- End Google tag (gtag.js) -->
        <!-- Matomo -->
        <script>
         var _paq = window._paq = window._paq || [];
         _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
         _paq.push(["setCookieDomain", "*.appliedbrainresearch.com"]);
         _paq.push(["setDomains", ["*.appliedbrainresearch.com","*.edge.nengo.ai","*.forum.nengo.ai","*.nengo.ai"]]);
         _paq.push(["enableCrossDomainLinking"]);
         _paq.push(["setDoNotTrack", true]);
         _paq.push(['trackPageView']);
         _paq.push(['enableLinkTracking']);
         (function() {
           var u="https://appliedbrainresearch.matomo.cloud/";
           _paq.push(['setTrackerUrl', u+'matomo.php']);
           _paq.push(['setSiteId', '3']);
           var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
           g.async=true; g.src='//cdn.matomo.cloud/appliedbrainresearch.matomo.cloud/matomo.js'; s.parentNode.insertBefore(g,s);
         })();
        </script>
        <!-- End Matomo Code -->
    """,

The doctest_setup config option contains a list of Python statements that should be executed before the code in .. testcode:: blocks, which are run with the sphinx.ext.doctest extension.

[32]:
nengobones_yml = """
docs_conf_py:
    doctest_setup:
        - import nengo
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py")
# -*- coding: utf-8 -*-
#
# Automatically generated by nengo-bones, do not edit this file directly

import pathlib

import eg_package

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.doctest",
    "sphinx.ext.githubpages",
    "sphinx.ext.intersphinx",
    "sphinx.ext.mathjax",
    "sphinx.ext.todo",
    "nbsphinx",
    "nengo_sphinx_theme",
    "nengo_sphinx_theme.ext.sourcelinks",
    "notfound.extension",
    "numpydoc",
]

# -- sphinx.ext.autodoc
autoclass_content = "both"  # class and __init__ docstrings are concatenated
autodoc_default_options = {"members": None}
autodoc_member_order = "bysource"  # default is alphabetical

# -- sphinx.ext.doctest
doctest_global_setup = """
import eg_package
import nengo
"""

# -- sphinx.ext.intersphinx
intersphinx_mapping = {
    "nengo": ("https://www.nengo.ai/nengo/", None),
    "numpy": ("https://numpy.org/doc/stable", None),
    "python": ("https://docs.python.org/3", None),
}

# -- sphinx.ext.todo
todo_include_todos = True

# -- nbsphinx
nbsphinx_timeout = -1

# -- notfound.extension
notfound_template = "404.html"
notfound_urls_prefix = "/eg-package/"

# -- numpydoc config
numpydoc_show_class_members = False

# -- nengo_sphinx_theme.ext.sourcelinks
sourcelinks_module = "eg_package"
sourcelinks_url = "https://github.com/eg-org/eg-package"

# -- sphinx
nitpicky = True
exclude_patterns = [
    "_build",
    "**/.ipynb_checkpoints",
]
linkcheck_timeout = 30
source_suffix = ".rst"
source_encoding = "utf-8"
master_doc = "index"
linkcheck_ignore = [r"http://localhost:\d+"]
linkcheck_anchors = True
default_role = "py:obj"
pygments_style = "sphinx"
user_agent = "eg_package"

project = "Example Project"
authors = "Applied Brain Research"
copyright = "2024-2024 Applied Brain Research"
version = ".".join(eg_package.__version__.split(".")[:2])  # Short X.Y version
release = eg_package.__version__  # Full version, with tags

# -- HTML output
templates_path = ["_templates"]
html_static_path = ["_static"]
html_theme = "nengo_sphinx_theme"
html_title = f"Example Project {release} docs"
htmlhelp_basename = "Example Project"
html_last_updated_fmt = ""  # Default output format (suppressed)
html_show_sphinx = False
html_favicon = str(pathlib.Path("_static", "favicon.ico"))
html_theme_options = {
    "nengo_logo": "general-full-light.svg",
    "nengo_logo_color": "#a8acaf",
    "analytics": """
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-GT8XEDLTMJ"></script>
        <script>
         window.dataLayer = window.dataLayer || [];
         function gtag(){dataLayer.push(arguments);}
         gtag('js', new Date());
         gtag('config', 'G-GT8XEDLTMJ');
        </script>
        <!-- End Google tag (gtag.js) -->
        <!-- Matomo -->
        <script>
         var _paq = window._paq = window._paq || [];
         _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
         _paq.push(["setCookieDomain", "*.appliedbrainresearch.com"]);
         _paq.push(["setDomains", ["*.appliedbrainresearch.com","*.edge.nengo.ai","*.forum.nengo.ai","*.nengo.ai"]]);
         _paq.push(["enableCrossDomainLinking"]);
         _paq.push(["setDoNotTrack", true]);
         _paq.push(['trackPageView']);
         _paq.push(['enableLinkTracking']);
         (function() {
           var u="https://appliedbrainresearch.matomo.cloud/";
           _paq.push(['setTrackerUrl', u+'matomo.php']);
           _paq.push(['setSiteId', '3']);
           var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
           g.async=true; g.src='//cdn.matomo.cloud/appliedbrainresearch.matomo.cloud/matomo.js'; s.parentNode.insertBefore(g,s);
         })();
        </script>
        <!-- End Matomo Code -->
    """,
}

The html_redirects config option contains a mapping from original locations to new locations for generated HTML files that have been moved.

[33]:
nengobones_yml = """
docs_conf_py:
    html_redirects:
        old_file.html: new-file.html
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["extensions", "html_redirects"])
extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.doctest",
    "sphinx.ext.githubpages",
    "sphinx.ext.intersphinx",
    "sphinx.ext.mathjax",
    "sphinx.ext.todo",
    "nbsphinx",
    "nengo_sphinx_theme",
    "nengo_sphinx_theme.ext.redirects",
    "nengo_sphinx_theme.ext.sourcelinks",
    "notfound.extension",
    "numpydoc",
html_redirects = [
    ("old_file.html", "new-file.html"),

The autoautosummary_change_modules config option allows the module of classes/functions to be changed in autoautosummary or automodule directives. For example, this can be used so that nengo.ensemble.Ensemble shows up as nengo.Ensemble in the documentation. Note that this depends on the nengo_sphinx_theme.ext.autoautosummary extension.

[34]:
nengobones_yml = """
docs_conf_py:
    autoautosummary_change_modules:
        nengo:
            - nengo.ensemble.Ensemble
            - nengo.connection.Connection
        nengo.another_module:
            - nengo.some.function
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["autoautosummary_change_modules"])
autoautosummary_change_modules = {
    "nengo": [
        "nengo.ensemble.Ensemble",
        "nengo.connection.Connection",
    ],
    "nengo.another_module": [
        "nengo.some.function",
    ],

The one_page config option can be used for projects that include all of their documentation on a single index page.

[35]:
nengobones_yml = """
docs_conf_py:
    one_page: True
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents("docs/conf.py", sections=["html_theme_options"])
html_theme_options = {
    "nengo_logo": "general-full-light.svg",
    "nengo_logo_color": "#a8acaf",
    "analytics": """
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-GT8XEDLTMJ"></script>
        <script>
         window.dataLayer = window.dataLayer || [];
         function gtag(){dataLayer.push(arguments);}
         gtag('js', new Date());
         gtag('config', 'G-GT8XEDLTMJ');
        </script>
        <!-- End Google tag (gtag.js) -->
        <!-- Matomo -->
        <script>
         var _paq = window._paq = window._paq || [];
         _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
         _paq.push(["setCookieDomain", "*.appliedbrainresearch.com"]);
         _paq.push(["setDomains", ["*.appliedbrainresearch.com","*.edge.nengo.ai","*.forum.nengo.ai","*.nengo.ai"]]);
         _paq.push(["enableCrossDomainLinking"]);
         _paq.push(["setDoNotTrack", true]);
         _paq.push(['trackPageView']);
         _paq.push(['enableLinkTracking']);
         (function() {
           var u="https://appliedbrainresearch.matomo.cloud/";
           _paq.push(['setTrackerUrl', u+'matomo.php']);
           _paq.push(['setSiteId', '3']);
           var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
           g.async=true; g.src='//cdn.matomo.cloud/appliedbrainresearch.matomo.cloud/matomo.js'; s.parentNode.insertBefore(g,s);
         })();
        </script>
        <!-- End Matomo Code -->
    """,
    "one_page": True,

Finally, the sphinx_options config option can be used to set arbitrary options of the form var = val in the conf.py file.

[36]:
nengobones_yml = """
docs_conf_py:
    sphinx_options:
        an_option: "'a string value'"
        another_option: ["a", "list", "value"]
"""
write_yml(nengobones_yml)

!bones generate docs-conf-py
display_contents(
    "docs/conf.py",
    sections=["default_role", "pygments_style", "an_option", "another_option"],
)
default_role = "py:obj"
pygments_style = "sphinx"
an_option = "a string value"
another_option = ["a", "list", "value"]

pyproject.toml config

The pyproject.toml template has two available configurations: - black_exclude: A list of patterns to exclude during black formatting. - isort_exclude: A list of patterns to exclude during isort formatting.

For each configuration option, the entries must be valid regular expressions.

When you add this file to your .nengobones.yml file, you should also add something to your documentation to indicate that users should configure their editor to run black and/or isort automatically.

[37]:
nengobones_yml = """
pyproject_toml:
    black_exclude:
        - project/ignore_me.py
    isort_exclude:
        - project/ignore_me/**
"""
write_yml(nengobones_yml)

!bones generate pyproject-toml
display_contents("pyproject.toml")
# Automatically generated by nengo-bones, do not edit this file directly

[build-system]
requires = ["setuptools<64", "wheel"]

[tool.black]
target-version = ['py38']
force_exclude = '''
(
    project/ignore_me.py
)
'''

[tool.isort]
profile = "black"
src_paths = ["eg_package"]
skip_gitignore = true
extend_skip_glob = [
    "project/ignore_me/**"
]

[tool.docformatter]
wrap-summaries = 88
wrap-descriptions = 81
pre-summary-newline = true

py.typed config

The py.typed file lets other Python packages know that your package has type hints. The file has no contents, so there is nothing to configure, but we use the presence of this config section to generate the file and modify other templates, such as adding a mypy check in .ci/static.sh. See PEP-561 for more context.

[38]:
nengobones_yml = """
py_typed: {}
"""
write_yml(nengobones_yml)

!bones generate py-typed
list(pathlib.Path("eg_package").iterdir())
[38]:
[PosixPath('eg_package/py.typed')]

version.py config

The version.py file is used to store version information about the package. It supports both Semantic and Calendar versioning (controlled by the type option). For semantic versioning the user should specify the major, minor, and patch options. For both types the user should specify the release option, which should be True for releases and False otherwise.

[39]:
nengobones_yml = """
version_py:
    type: semver
    major: 1
    minor: 2
    patch: 3
    release: true
"""
write_yml(nengobones_yml)

!bones generate version-py
from eg_package import version  # pylint: disable=wrong-import-order

print(version.version)
1.2.3
[40]:
nengobones_yml = """
version_py:
    type: calver
    release: false
"""
write_yml(nengobones_yml)

!bones generate version-py
reload(version)
print(version.version)
24.2.28.dev0

Github Actions

NengoBones provides a number of Actions which can be used with Github Actions to automate common parts of a workflow. These can be used like

jobs:
  ...
  steps:
    ...
    - uses: nengo/nengo-bones/actions/generate-and-check@main

See the nengo-bones/actions directory for the available actions. See the Github Actions documentation for instructions on using Github Actions. The .github/workflows/ci.yml file in the NengoBones repository may also be a helpful starting point.


[41]:
# clean up the temporary files generated by this notebook

files = list(nengo_bones.all_files) + [
    ".nengobones.yml",
    "test.sh",
    "test2.sh",
    "static.sh",
]

for file in files:
    path = pathlib.Path(file)
    if path.exists():
        path.unlink()