| 1 |
Coding conventions |
| 2 |
================== |
| 3 |
General recommendations |
| 4 |
----------------------- |
| 5 |
Syntax is chosen as much as possible from the user point of view, |
| 6 |
to reflect the concepts as directly as possible. Ideally, a Brian script |
| 7 |
should be readable by someone who doesn't know Python or Brian, although this |
| 8 |
isn't always possible. Function, class and keyword argument names should be |
| 9 |
explicit rather than abbreviated and consistent across Brian. See Romain's paper |
| 10 |
`On the design of script languages for neural simulators |
| 11 |
<http://briansimulator.org/WordPress/wp-content/uploads/2012/05/On-the-design-of-script-languages-for-neural-simulation.pdf>`__ |
| 12 |
for a discussion. |
| 13 |
|
| 14 |
.. _code_style: |
| 15 |
|
| 16 |
Code style |
| 17 |
~~~~~~~~~~ |
| 18 |
|
| 19 |
We use the `PEP-8 coding conventions <https://www.python.org/dev/peps/pep-0008/>`__ |
| 20 |
for our code, and use the `ruff formatting tool <https://docs.astral.sh/ruff>`__ to |
| 21 |
enforce a consistent code style. To make sure your code is formatted in the same way, |
| 22 |
you can either `integrate ruff with your editor/IDE <https://docs.astral.sh/ruff/editors/setup/>`__, |
| 23 |
or install the ``pre-commit`` tool |
| 24 |
(`pre-commit documentation <https://pre-commit.com/>`__), and install it as a "git hook" |
| 25 |
with ``pre-commit install``. This will automatically run ``ruff`` before each commit. |
| 26 |
In case that run changes the code formatting, it will reformat the relevant files, and you will have |
| 27 |
to ``git add`` these changes before doing the commit. For pull requests, this check will also be run |
| 28 |
automatically on the GitHub CI infrastructure. |
| 29 |
|
| 30 |
.. note:: |
| 31 |
|
| 32 |
In rare cases like manually aligned tables of related values, you can use |
| 33 |
``fmt: skip`` (for single lines), or ``fmt: off`` and ``fmt: on`` (for code blocks), |
| 34 |
to exclude code from ruff's formatting. Also note that the code formatting is only |
| 35 |
enforced for files in the ``brian2`` package itself, code examples in the |
| 36 |
documentation or examples and tutorials do not have to follow ruff's style. |
| 37 |
|
| 38 |
The code style includes the following conventions in particular: |
| 39 |
|
| 40 |
* Use 4 spaces instead of tabs per indentation level |
| 41 |
* Use spaces after commas and around the following binary operators: |
| 42 |
assignment (=), augmented assignment (+=, -= etc.), |
| 43 |
comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), |
| 44 |
Booleans (and, or, not). |
| 45 |
* Do *not* use spaces around the equals sign in keyword arguments or when |
| 46 |
specifying default values. Neither put spaces immediately inside parentheses, |
| 47 |
brackets or braces, immediately before the open parenthesis that starts the |
| 48 |
argument list of a function call, or immediately before the open parenthesis |
| 49 |
that starts an indexing or slicing. |
| 50 |
* Avoid using a backslash for continuing lines whenever possible, instead use |
| 51 |
Python's implicit line joining inside parentheses, brackets and braces. |
| 52 |
|
| 53 |
Imports |
| 54 |
~~~~~~~ |
| 55 |
Imports should be on different lines (e.g. do not use ``import sys, os``) and should be |
| 56 |
grouped in the following order, using blank lines between each group: |
| 57 |
|
| 58 |
1. standard library imports |
| 59 |
2. third-party library imports (e.g. numpy, scipy, sympy, ...) |
| 60 |
3. brian imports |
| 61 |
|
| 62 |
This rule is enforced by ruff as well. |
| 63 |
|
| 64 |
.. note:: |
| 65 |
|
| 66 |
In rare cases, where logical grouping makes more sense that ``isort``'s ordering, |
| 67 |
or when the order of imports matters, you can skip sorting imports in a file by |
| 68 |
including the comment ``# isort:skip_file``. |
| 69 |
|
| 70 |
Additional rules for imports: |
| 71 |
|
| 72 |
* Use absolute imports for everything outside of "your" package, e.g. if you |
| 73 |
are working in `brian2.equations`, import functions from the stringtools |
| 74 |
modules via ``from brian2.utils.stringtools import ...``. Use the full path |
| 75 |
when importing, e.g. do ``from brian2.units.fundamentalunits import seconds`` |
| 76 |
instead of ``from brian2 import seconds``. |
| 77 |
* Use "new-style" relative imports for everything in "your" package, e.g. in |
| 78 |
``brian2.codegen.functions.py`` import the `Function` class as |
| 79 |
``from .specifiers import Function``. |
| 80 |
* Do not use wildcard imports (``from brian2 import *``), instead import only the |
| 81 |
identifiers you need, e.g. ``from brian2 import NeuronGroup, Synapses``. For |
| 82 |
packages like numpy that are used a lot, use ``import numpy as np``. But |
| 83 |
note that the user should still be able to do something like |
| 84 |
``from brian2 import *`` (and this style can also be freely used in examples |
| 85 |
and tests, for example). Modules always have to use the ``__all__`` mechanism |
| 86 |
to specify what is being made available with a wildcard import. As an |
| 87 |
exception from this rule, the main ``brian2/__init__.py`` may use wildcard |
| 88 |
imports. |
| 89 |
|
| 90 |
String formatting |
| 91 |
----------------- |
| 92 |
In general, we use Python `f-strings <https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals>`__ |
| 93 |
instead of the ``.format`` method or the `%` operator to format strings. For example, rather use:: |
| 94 |
|
| 95 |
raise KeyError(f"Unknown variable '{var}'") # ✔ |
| 96 |
|
| 97 |
instead of:: |
| 98 |
|
| 99 |
raise KeyError("Unknown variable '{}'".format(var)) # ❌ |
| 100 |
raise KeyError("Unknown variable %s" % var) # ❌ |
| 101 |
|
| 102 |
There are some corner cases where it still makes sense to use either of these, though. |
| 103 |
The `~str.format` method can be useful when processing several strings instead of single literals:: |
| 104 |
|
| 105 |
formatted = [] |
| 106 |
for s in strings: |
| 107 |
formatted.append(s.format(**values)) |
| 108 |
|
| 109 |
The `%` operator, or string concatenation, can be used when dealing with strings that contain curly braces, which would |
| 110 |
become difficult to read as an f-string:: |
| 111 |
|
| 112 |
latex_code = r'\begin{equation}%s\end{equation}' % equation # OK |
| 113 |
latex_code = r'\begin{equation}' + equation + r'\end{equation}' # OK |
| 114 |
|
| 115 |
Python does not make a difference between single quotation marks and double quotation marks. For consistency, |
| 116 |
we use ruff's style that double quotes (i.e. `"..."`) are used everywhere, except when |
| 117 |
this would lead to escaping of double quotation marks within the string itself |
| 118 |
(e.g. for ``include = f'#include "{header_file}"'``). When you need to display text to |
| 119 |
the user (e.g. in exception messages), use single quotation marks to highlight words to |
| 120 |
avoid this situation (e.g. `"The 'item' value should not be 0."`). |
| 121 |
|
| 122 |
Commits only changing the style |
| 123 |
------------------------------- |
| 124 |
We have sometimes made big commits updating the style in our code, which can make using tools like ``git blame`` more |
| 125 |
difficult, since many lines are affected by such commits. We add the references to such commits to a file |
| 126 |
``.git-blame-ignore-revs`` in the main directory, and you can tell ``git blame`` to ignore these commits with:: |
| 127 |
|
| 128 |
git config blame.ignoreRevsFile .git-blame-ignore-revs |