The KernelPool context manager

The KernelPool context manager provides a convenient way to load, and unload SPICE kernels, guaranteeing that the kernel database will still be cleared if an exception is raised.

Warning

KernelPool uses spice.kclear() to temporarily unload previously loaded kernels. Thus, any user-defined variable will be permanently deleted from the kernel pool. Check the Compatibility with kernel-pool assignment functions section for a detailed explanation.

Basic usage

A typical program using SpiceyPy starts with spice.furnsh(), and ends with spice.kclear() or spice.unload(). If an exception is raised while loading kernels or executing user code, spice.kclear() won’t be executed, and the kernel database won’t be cleared. To avoid this issue, a try...finally clause is often used:

try:
    spice.furnsh("path/to/kernels")
    # user code
finally:
    spice.kclear()

The KernelPool context manager provides the exact same result as the previous example, but with a simpler syntax.

with spice.KernelPool("path/to/kernels"):

    # user code

Local and global kernels

Each of the kernels used to initialize the context manager is known as a local kernel. Any kernel loaded before the with statement is known as a global kernel. KernelPool creates an isolated environment from which only local kernels are accessible.

spice.furnsh(["A", "B"])
function_1()
with spice.KernelPool(["A", "C", "D"]):
    function_2()
function_3()

In the previous example, function_1() and function_3() have access to kernels A, and B (global kernels); while function_2() has access to kernels A, C, and D (local kernels).

Compatibility with kernel-pool assignment functions

In order to create an isolated environment for local kernels, KernelPool performs a series of steps:

  1. Unload global kernels using spice.kclear().

  2. Load local kernels using spice.furnsh().

  3. Execute user code.

  4. Unload local kernels using spice.kclear().

  5. Load global kernels using spice.furnsh().

In addition to spice.furnsh(), SpiceyPy provides a series of functions (kernel-pool assignment functions) to add user-defined variables to the kernel pool, such as spice.pcpool(), spice.pdpool(), or spice.pipool(). As KernelPool unloads, and then reloads global kernels, these user defined variables are not restored after the with statement.

spice.furnsh(["A", "B"])
spice.pipool("VAR", [13])
function_1()
with spice.KernelPool(["A", "C", "D"]):
    function_2()
function_3()

In this example, though function_1() has access to VAR, function_2() and function_3() don’t.

Note

For more information about SPICE kernels, refer to the Kernel required reading document of the NAIF. The Kernel Management section of this document provides detailed explanations regarding the kernel pool, the kernel database, kernel pool assignment functions, and the behavior of spice.furnsh(), spice.kclear() and spice.unload().