Skip to content
Specular Differentiation

specular.backends.set_backend

set_backend(name)

Select a backend for subsequent calculations in the current execution context.

Parameters

Name Type Description
name str One of "numpy", "numba", or "jax". Names are case-sensitive.

Returns

None — The selected backend is stored in the current context.

Notes

The backend is imported and validated before the selection changes. A missing optional dependency is reported immediately as an ImportError, leaving the previous selection in place. Install the corresponding extra before selecting Numba or JAX; see the backend user guide.

A non-string name raises TypeError; an unsupported string raises ValueError. Other errors from backend loading propagate to the caller.

The selection persists in the current context until changed again. Changes in an asynchronous context do not overwrite the selection in other contexts. A fresh execution context starts with NumPy; a thread that explicitly inherits a context inherits its selection. For a temporary override that restores the previous selection, use use_backend.

This function is also available as specular.set_backend.

Examples

import specular

specular.set_backend("numpy")
value = specular.derivative(lambda x: x * x, 2.0)
print(specular.get_backend(), value)
Source code in specular/backends/_registry.py
156
157
158
159
160
161
162
163
164
165
def set_backend(name: str) -> None:
    """Select a backend for subsequent calls in the current context.

    The backend is imported immediately so a missing optional dependency is
    reported at configuration time instead of at the first calculation.
    """

    selected = _validate_backend(name)
    _load_backend(selected)
    _current_backend.set(selected)