This guide describes common conventions, guidelines, and strategies for contributing code to PlasmaPy. The purpose of this guide is not to provide a set of rigid guidelines that must be adhered to, but rather to provide a common framework that helps us develop PlasmaPy together as a community.
Having a shared coding style makes it easier to understand code written by multiple contributors. The particulars of the coding style are not as important as consistency, readability, and maintainability.
This guide can (and should!) be regularly refined by the PlasmaPy community as we collectively learn new practices and our shared coding style changes. Please feel free to propose revisions to this guide by submitting a pull request or by bringing up an idea at a community meeting.
Write short functions that do exactly one thing with no side effects.
Use NumPy array options instead of
forloops to make code more compact, readable, and performant.
Some plasma parameters depend on more than one
Quantityof the same physical type. For example, when reading the following line of code, we cannot immediately tell which is the electron temperature and which is the ion temperature.
f(1e6 * u.K, 2e6 * u.K)
Spell out the parameter names to improve readability and reduce the likelihood of errors.
f(T_i=1e6 * u.K, T_e=2e6 * u.K)
Similarly, when a function has parameters named
T_i, these parameters should be made keyword-only to avoid ambiguity and reduce the chance of errors.
def f(*, T_i, T_e): ...
__ne__methods of a class should not raise exceptions. If the comparison for equality is being made between objects of different types, these methods should return
Falseinstead. This behavior is for consistency with operations like
1 == "1"which will return
Limit usage of
lambdafunctions to one-liners, such as when defining the default factory of a
defaultdict). For anything longer than one line, use
List and dictionary comprehensions can be used for simple
>>> [x**2 for x in range(17) if x % 2 == 0] [0, 4, 16, 36, 64, 100, 144, 196, 256]
Avoid putting any significant implementation code in
__init__.pyfiles. Implementation details should be contained in a different file, and then imported into
Avoid defining global variables when possible.
assertstatements only in tests.
Use formatted string literals (f-strings) instead of legacy formatting for strings.
Functions that accept array_like or
Quantityinputs should accept and return
nan(not a number) values. This guideline applies when
nanis the input as well as when
nanvalues are included in an array.
Do not use mutable objects as default values in the function or method declaration. This can lead to unexpected behavior.
>>> def function(l=): ... l.append("x") ... print(l) ... >>> function() ['x'] >>> function() ['x', 'x']
pathlibwhen working with paths to data files.
Names are our most fundamental means of communicating the intent and purpose of code. Wisely chosen names can greatly improve the understandability of code, while inadequate names can obfuscate what the code is supposed to be doing.
PlasmaPy generally uses the PEP 8 conventions for variable names.
Use lowercase words separated by underscores for function and variable names (e.g.,
Use capitalized words without separators when naming a class (e.g.,
ClassName), but keep acronyms capitalized (e.g.,
Use capital letters words separated by underscores when naming constants (e.g.,
There are some situations in PlasmaPy which justify a departure from the PEP 8 conventions.
Functions based on plasma parameters that are named after people may be capitalized (e.g.,
Capital letters may be used for a variable when it matches the standard usage in plasma science (e.g.,
Bfor magnetic field and
Choose names that are pronounceable to make them more memorable and compatible with text-to-speech technology.
Choose names will produce more relevant results when searching the internet.
Avoid unnecessary abbreviations, as these make code harder to read. Prefer clarity over brevity, except for code that is used frequently and interactively (e.g., cd or ls).
Measure the length of a variable not by the number of characters, but rather by the time needed to understand its meaning.
By this measure,
cggglmis significantly longer than
Avoid ambiguity. Does
tempmean “temperature”, “temporary”, or “template”?
_eto a variable name to indicate that it refers to electrons,
_ifor ions, and
_pfor protons (e.g.,
Python allows alphanumeric Unicode characters to be used in object names (e.g.,
φυσική). These characters may be used for internal code when doing so improves readability (i.e., to match a commonly used symbol) and in Jupyter notebooks.
If a plasma parameter has multiple names, then use the name that provides the most physical insight. For example,
gyrofrequencyindicates gyration but
It is usually preferable to name a variable after its name rather than its symbol. An object named
Debye_lengthis more broadly understandable and searchable than
lambda_D. However, there are some exceptions to this guideline.
Symbols used widely across plasma science can be used with low risk of confusion, such as \(T\) for temperature or \(β\) for plasma
Symbols that are defined in docstrings can be used with decreased likelihood of confusion.
Sometimes code that represents an equation will be more readable if the Unicode characters for the symbols are used, especially for complex equations. For someone who is familiar with the symbols,
λ = c / νwill be more readable than
lambda = c / nuor
wavelength = speed_of_light / frequency.
If an implementation is based on a journal article, then variable names may be based on the symbols used in that article. The article should be cited in the appropriate docstring so that it appears in the Bibliography.
To mark that an object is not part of PlasmaPy’s public API, begin its name with a leading underscore (e.g.,
_private_variable). Private variables should not be included in
Avoid single character variable names except for standard plasma physics symbols (e.g.,
B) or as indices in
Avoid encoding type information in a variable name.
Intermediate variable names can provide additional context and meaning. For example, suppose we have a conditional operating on a complicated expression:
if u < x < u and v < y < v and w < z < w: ...
Defining an intermediate variable allows us to communicate the meaning and intent of the expression.
point_is_in_grid_cell = u < x < u and v < y < v and w < z < w if point_is_in_grid_cell: ...
forloops, this may take the form of assignment expressions with the walrus operator (
Error messages are a vital but underappreciated form of documentation. A good error message can help someone pinpoint the source of a problem in seconds, while a cryptic or missing error message can lead to hours of frustration.
Use error messages to indicate the source of the problem while providing enough information for the user to troubleshoot it. When possible, make it clear what the user should do next.
Include diagnostic information when appropriate. For example, if an error occurred at a single index in an array operation, then including the index where the error happened can help the user better understand the cause of the error.
Write error messages that are concise when possible, as users often skim or skip long error messages.
Avoid including information that is irrelevant to the source of the problem.
Write error messages in language that is plain enough to be understandable to someone who is undertaking their first research project.
If necessary, technical information may be placed after a plain language summary statement.
Alternatively, an error message may reference a docstring or a page in the narrative documentation.
Write error messages that are friendly, supportive, and helpful. Error message should never be condescending or blame the user.
Use standard abbreviations for imported packages:
For infrequently used objects, import the package, subpackage, or module rather than the individual code object. Including more of the namespace provides contextual information that can make code easier to read. For example,
json.loadsis more readable than using only
For frequently used objects (e.g.,
Particle) and type hint annotations (e.g.,
Real), import the object directly instead of importing the package, subpackage, or module. Including more of the namespace would increase clutter and decrease readability without providing commensurately more information.
Use absolute imports (e.g.,
from plasmapy.particles import Particle) rather than relative imports (e.g.,
from ..particles import Particle).
Do not use star imports (e.g.,
from package.subpackage import *), except in very limited situations.
Each release of PlasmaPy should support all minor versions of Python that have been released in the prior 42 months, and all minor versions of NumPy that have been released in the last 24 months. This schedule was proposed in NumPy Enhancement Proposal 29 for the scientific Python ecosystem, and has been adopted by upstream packages such as NumPy, matplotlib, and Astropy.
Tools like pyupgrade help automatically upgrade the code base to the minimum supported version of Python for the next release.
PlasmaPy should generally allow all feature releases of required dependencies made in the last ≲ 24 months, unless a more recent release includes a needed feature or bugfix.
Only set maximum or exact requirements (e.g.,
numpy <= 1.22.3or
scipy == 1.7.2) when absolutely necessary. After setting a maximum or exact requirement, create a GitHub issue to remove that requirement.
Maximum requirements can lead to version conflicts when installed alongside other packages. It is preferable to update PlasmaPy to become compatible with the latest versions of its dependencies than to set a maximum requirement.
Minor versions of Python are generally released in October of each year. However, it may take a few months before packages like NumPy and Numba become compatible with the newest minor version of Python.
Transforming particle-like arguments into particle objects
Validating Quantity arguments
validate_quantities() to verify function arguments and impose
@validate_quantities def magnetic_pressure(B: u.T) -> u.Pa: return B**2 / (2 * const.mu0)
Special function categories
Aliases are intended to give users the option for shortening their code while maintaining some readability and explicit meaning. As such, aliases are given to functionality that already has a widely-used symbol in plasma literature.
Here is a minimal example of an alias
would be defined in
__all__ = ["function"] __aliases__ = ["f_"] __all__ += __aliases__ def function(): ... f_ = function """Alias to `~plasmapy.subpackage.module.function`."""
Aliases should only be defined for frequently used plasma parameters which already have a symbol that is widely used in the community’s literature. This is to ensure that the abbreviated function name is still reasonably understandable. For example,
cwp_is a shortcut for \(c/ω_p\).
The name of an alias should end with a trailing underscore.
An alias should be defined immediately after the original function.
Each alias should have a one-line docstring that refers users to the original function.
The name of the original function should be included in
__all__near the top of each module, and the name of the alias should be included in
__aliases__, which will then get appended to
__all__. This is done so both the alias and the original function get properly documented.
Aliases are intended for end users, and should not be used in PlasmaPy or other collaborative software development efforts because of reduced readability and searchability for someone new to plasma science.
Most functions in
Quantity instances as
arguments and use
validate_quantities() to verify that
arguments are valid. The use of
Quantity operations and validations do
not noticeably impact performance during typical interactive use, but
the performance penalty can become significant for numerically intensive
A lite-function is an optimized version of another
function that accepts numbers and NumPy arrays in assumed SI units.
Lite-functions skip all validations and instead prioritize
performance. Most lite-functions are defined in
formulary functions, no validations are
performed on the arguments provided to a lite-function for
the sake of computational efficiency. When using
lite-functions, it is vital to double-check your
Here is a minimal example of a lite-function
that corresponds to
function as would be defined in
__all__ = ["function"] __lite_funcs__ = ["function_lite"] from numbers import Real from numba import njit from plasmapy.utils.decorators import bind_lite_func, preserve_signature __all__ += __lite_funcs__ @preserve_signature @njit def function_lite(v: Real) -> Real: """ The lite-function which accepts and returns real numbers in assumed SI units. """ ... @bind_lite_func(function_lite) def function(v): """A function that accepts and returns Quantity arguments.""" ...
Lite-functions assume SI units for all arguments that represent physical quantities.
Lite-functions should be defined immediately before the normal version of the function.
Lite-functions should be used by their associate non-lite counterpart, except for well reasoned exceptions. This is done to reduce code duplication.
If a lite-function is decorated with something like
@njit, then it should also be decorated with
preserve_signature. This preserves the function signature so interpreters can still give hints about function arguments.
The name of the original function should be included in
__all__near the top of each module, and the name of the lite-function should be included in
__lite_funcs__, which will then get appended to
__all__. This is done so both the lite-function and the original function get properly documented.
>>> import astropy.units as u >>> 5 * u.m / u.s <Quantity 5. m / s>
Only SI units should be used within PlasmaPy, unless there is a strong justification to do otherwise. Example notebooks may occasionally use other unit systems to show the flexibility of
Avoid using electron-volts as a unit of temperature within PlasmaPy because it is defined as a unit of energy. However, functions in
plasmapy.formularyand elsewhere should accept temperatures in units of electron-volts, which can be done using
>>> (1 * u.eV).to(u.K, equivalencies=u.temperature_energy()) 11604.518...
The names of SI units should not be capitalized except at the beginning of a sentence, including when they are named after a person. The sole exception is “degree Celsius”.
Avoid using implicit default particle assumptions for function arguments (see issue #453).
particle_input()decorator can automatically transform a particle-like argument into a
ParticleListinstance when the corresponding parameter is decorated with
If we use
get_particleon something particle-like, it will return the corresponding particle object.
>>> return_particle("p+") Particle("p+")
The documentation for
particle_input()describes ways to ensure that the particle meets certain categorization criteria.
Equations and Physical Formulae
Physical formulae should be inputted without first evaluating all of the physical constants. For example, the following line of code obscures information about the physics being represented:
omega_ce = 1.76e7*(B/u.G)*u.rad/u.s # doctest: +SKIP
In contrast, the following line of code shows the exact formula which makes the code much more readable.
omega_ce = (e * B) / (m_e * c) # doctest: +SKIP
The origins of numerical coefficients in formulae should be documented.
Docstrings should describe the physics associated with these quantities in ways that are understandable to students who are taking their first course in plasma physics while still being useful to experienced plasma physicists.
Unit conversions involving angles must be treated with care. Angles are
dimensionless but do have units. Angular velocity is often given in
units of radians per second, though dimensionally this is equivalent to
inverse seconds. Astropy will treat radians dimensionlessly when using
dimensionless_angles equivalency, but
dimensionless_angles does not account for the multiplicative
factor of \(2π\) that is used when converting between frequency
(1/s) and angular frequency (rad/s). An explicit way to do this
conversion is to set up an equivalency between cycles/s and Hz:
import astropy.units as u f_ce = omega_ce.to(u.Hz, equivalencies=[(u.cy/u.s, u.Hz)]) # doctest: +SKIP
dimensionless_angles does work when dividing a velocity by
an angular frequency to get a length scale:
d_i = (c/omega_pi).to(u.m, equivalencies=u.dimensionless_angles()) # doctest: +SKIP
Examples in PlasmaPy are written as Jupyter notebooks, taking advantage of their mature ecosystems. They are located in docs/notebooks. nbsphinx takes care of executing them at documentation build time and including them in the documentation.
Please note that it is necessary to store notebooks with their outputs stripped (use the “Edit -> Clear all” option in JupyterLab and the “Cell -> All Output -> Clear” option in the “classic” Jupyter Notebook). This accomplishes two goals:
helps with versioning the notebooks, as binary image data is not stored in the notebook
signals nbsphinx that it should execute the notebook.
In the future, verifying and running this step may be automated via a GitHub bot. Currently, reviewers should ensure that submitted notebooks have outputs stripped.
If you have an example notebook that includes packages unavailable in
the documentation building environment (e.g.,
bokeh) or runs some
heavy computation that should not be executed on every commit, keep the
outputs in the notebook but store it in the repository with a
preexecuted_ prefix (e.g.,
Compatibility with Prior Versions of Python, NumPy, and Astropy
PlasmaPy should support at least the minor versions of Python initially released 42 months prior to a planned project release date.
PlasmaPy should support at least the 3 latest minor versions of Python.
PlasmaPy should support minor versions of NumPy initially released in the 24 months prior to a planned project release date or the oldest version that supports the minimum Python version (whichever is higher).
PlasmaPy should support at least the 3 latest minor versions of NumPy and Astropy.
The required major and minor version numbers of upstream packages may only change during major or minor releases of PlasmaPy, and never during patch releases.
Exceptions to these guidelines should only be made when there are major improvements or fixes to upstream functionality or when other required packages have stricter requirements.
PlasmaPy has a set of asv benchmarks that monitor performance of its functionalities. This is meant to protect the package from performance regressions. The benchmarks can be viewed at benchmarks. They are generated from results located in benchmarks-repo. Detailed instructions on writing such benchmarks can be found at asv-docs. Up-to-date instructions on running the benchmark suite will be located in the README file of benchmarks-repo.