Context API#

Context packages backend operations and the default dtype. Spaces, operators, and functionals store a normalized context and use it for array construction and conversion.

Validation policy is not part of a context: check_level belongs to the bound object, so two objects on the same backend and dtype may validate at different strictness. Use check_level="none", "cheap", "standard", or "strict" on the object, or move the ambient default with set_check_level / use_check_level. The exported spacecore.CheckLevel literal is available for annotations. See Checking policy.

Context#

spacecore.Context

Backend operations plus the default dtype for new arrays.

class spacecore.Context(ops: BackendOps[DenseT] | type[BackendOps[DenseT]] | Context[DenseT], dtype: Any | None = None)[source]#
class spacecore.Context(ops: str, dtype: Any | None = None)

Bases: Generic[DenseT]

Backend operations plus the default dtype for new arrays.

A context owns no arrays; it creates and converts them. It is frozen, and check_level is deliberately not part of it (see spacecore.contextual.ContextBound).

Parameters:

Examples

Create a NumPy context and convert a Python list to a backend array.

>>> import numpy as np
>>> import spacecore as sc
>>> ctx = sc.Context(sc.NumpyOps(), dtype=np.float64)
>>> x = ctx.asarray([1.0, 2.0])
>>> x.dtype == np.dtype("float64")
True
__init__(ops: BackendOps[DenseT] | type[BackendOps[DenseT]] | Context[DenseT], dtype: Any | None = None) → None[source]#
__init__(ops: str, dtype: Any | None = None) → None

Validate and normalize the context after dataclass initialization.

Raises:

TypeError – If ops is not a BackendOps instance.

Parameters:
Return type:

None

assert_dense(x)[source]#

Return x if it is a dense array of this backend; raise TypeError otherwise.

Parameters:

x (Any)

Return type:

DenseT

assert_sparse(x)[source]#

Return x if it is a sparse array of this backend; raise TypeError otherwise.

Parameters:

x (Any)

Return type:

SparseArray

asarray(x)[source]#

Convert x to a dense backend array of dtype self.dtype.

Raises TypeError rather than silently dropping an imaginary part.

Parameters:

x (Any)

Return type:

DenseT

assparse(x)[source]#

Convert x to a sparse backend array of dtype self.dtype.

Raises TypeError if the backend has no sparse support, or if the conversion would drop an imaginary part.

Parameters:

x (Any)

Return type:

SparseArray

convert(x)[source]#

Convert a dense or sparse backend array to this context; raise NotImplementedError for anything else.

Parameters:

x (Any)

Return type:

ArrayLike

same_math(other)[source]#

Return whether other has equal backend ops and dtype.

The first-tier gate of every context-bound __eq__: it guarantees later value comparisons run on same-backend, same-dtype arrays. Not policy-configurable.

Parameters:

other (Any) – Object to compare against.

Returns:

True when other is a Context with equal ops and dtype.

Return type:

bool

same_backend(other)[source]#

Return whether other is a Context with equal ops, ignoring dtype.

The loosest context relation, used by context resolution: operands on one backend combine, and their dtypes are reconciled by conversion.

Parameters:

other (Any)

Return type:

bool

Context helpers#

spacecore.get_context

Return the currently active default SpaceCore context.

spacecore.set_context

Set the process-wide baseline SpaceCore context.

spacecore.use_context

Override the default context inside a with block.

spacecore.get_check_level

Return the ambient default validation level applied to new bound objects.

spacecore.set_check_level

Set the ambient default validation level applied to new bound objects.

spacecore.use_check_level

Override the ambient validation level inside a with block (thread/task-scoped, like use_context()).

spacecore.get_traced_check_level

Return the process-wide cap on check levels while a backend is tracing.

spacecore.set_traced_check_level

Set the process-wide cap on check levels while a backend is tracing.

spacecore.normalize_context

Normalize a context specification through the process-wide state.

spacecore.normalize_ops

Normalize backend operations through the process-wide state.

spacecore.resolve_context_priority

Resolve the context assigned to a newly created object.

spacecore.register_ops

Register a backend in the process-wide registry; registrations are never scoped.

  • get_context and set_context manage the global default context, and use_context overrides it for a block, scoped to the current thread or async task.

  • get_check_level / set_check_level / use_check_level do the same for the ambient validation level applied to newly constructed bound objects.

  • get_traced_check_level / set_traced_check_level cap every object’s level while a backend traces (jax.jit, jax.vmap, torch.compile); the default "none" turns checks off in traced code.

spacecore.get_context()[source]#

Return the currently active default SpaceCore context.

Resolves the use_context() override for this thread / task if one is installed, otherwise the process-wide baseline set by set_context().

Returns:

Active default context.

Return type:

Context

spacecore.set_context(ctx=None, dtype=None)[source]#

Set the process-wide baseline SpaceCore context.

Visible to every thread and async task. A use_context() override already in progress keeps winning until its block exits.

Parameters:
  • ctx (Context, BackendFamily, str, or None, optional) – Context or backend specification.

  • dtype (Any, optional) – Default dtype override.

Return type:

None

spacecore.use_context(ctx=None, dtype=None)[source]#

Override the default context inside a with block.

The override lives in a ContextVar: it is seen by the current thread and asyncio task only, and is undone on exit. Threads started inside the block see the baseline; run them under contextvars.copy_context() to pass it on.

Parameters:
  • ctx (Context, BackendFamily, str, or None, optional) – Context, or a backend family name such as "jax". None keeps the active context and applies only dtype.

  • dtype (dtype-like, optional) – Dtype for the scoped context; None keeps the current one.

Yields:

Context – The context in effect inside the block.

spacecore.get_check_level()[source]#

Return the ambient default validation level applied to new bound objects.

Returns:

The level that seeds a context-bound object constructed without an explicit check_level: the scoped override installed for this thread or task if there is one, otherwise the process-wide baseline.

Return type:

CheckLevel

spacecore.set_check_level(level)[source]#

Set the ambient default validation level applied to new bound objects.

check_level is a property of the context-bound object (space, operator, functional), not of the Context. This sets the process-wide default that seeds a new object when it is constructed without an explicit level.

Parameters:

level ({"none", "cheap", "standard", "strict"} or None) – New process-wide baseline. None restores the built-in default.

Return type:

None

spacecore.use_check_level(level)[source]#

Override the ambient validation level inside a with block (thread/task-scoped, like use_context()).

Parameters:

level ({"none", "cheap", "standard", "strict"} or None) – Level for the block; None keeps the ambient one.

Yields:

CheckLevel – The level in effect inside the block.

spacecore.get_traced_check_level()[source]#

Return the process-wide cap on check levels while a backend is tracing.

Returns:

The cap set by set_traced_check_level(); "none" by default.

Return type:

CheckLevel

spacecore.set_traced_check_level(level)[source]#

Set the process-wide cap on check levels while a backend is tracing.

Inside jax.jit, jax.vmap or torch.compile an object checks at the lower of its own level and this cap. "cheap" keeps shape and dtype checks, which run once at trace time and cost nothing in the compiled program; "standard" and above compare values, which a tracer cannot do.

Parameters:

level ({"none", "cheap", "standard", "strict"} or None) – New cap. None restores the default, "none".

Return type:

None

spacecore.normalize_context(ctx=None, dtype=None)[source]#

Normalize a context specification through the process-wide state.

Parameters:
  • ctx (Context, BackendFamily, str, or None, optional) – Context or backend specification.

  • dtype (Any, optional) – Default dtype override.

Returns:

Normalized context.

Return type:

Context

spacecore.normalize_ops(ops)[source]#

Normalize backend operations through the process-wide state.

Parameters:

ops (str, BackendFamily, BackendOps, type of BackendOps, or Context) – Backend operations specification.

Returns:

Normalized backend operations singleton.

Return type:

BackendOps

spacecore.resolve_context_priority(priority_ctx=None, *other_ctx)[source]#

Resolve the context assigned to a newly created object.

Parameters:
  • priority_ctx (Context, BackendFamily, str, or None, optional) – Explicit context that takes precedence when provided.

  • *other_ctx (object) – Objects or contexts used as fallback context sources.

Returns:

Resolved context.

Return type:

Context

spacecore.register_ops(ops)[source]#

Register a backend in the process-wide registry; registrations are never scoped.

Parameters:

ops (type of BackendOps) – Backend class to register.

Returns:

The registered class.

Return type:

type of BackendOps

Raises:

ContextConflictError – If the backend family is already registered.