Cache and restart reuse#

Compiled artifacts are cached on disk. After a Python kernel restart, you can import the cached module again without recompiling (as long as the runtime fingerprint matches).

This example demonstrates:

  • compiling a snippet

  • listing cached entries

  • importing the same module from the cache by key

  • (optional) showing cache stats

# Authors: The scikit-plots developers
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations

from typing import Any

from scikitplot import cython
def _print_entry_summary(entries: list[Any], limit: int = 5) -> None:
    """Print a stable cache listing summary."""
    print("Cache entries:", len(entries))
    if not entries:
        return

    # Print last few entries by whatever order list_cached returns.
    tail = entries[-limit:]
    print(f"Last {len(tail)} entries:")
    for e in tail:
        # CacheEntry is expected to have these (defaults exist).
        print("  - key:", getattr(e, "key", None))
        print("    module_name:", getattr(e, "module_name", None))
        print("    artifact_path:", getattr(e, "artifact_path", None))
        print("    created_utc:", getattr(e, "created_utc", None))

Generate python Module from python#

report = cython.check_build_prereqs(numpy=False)

if not report.get('cython', {}).get('ok'):
    print("Skipping compilation because build prerequisites are missing.")
    problems = report.get("problems", [])
    if problems:
        print("Problems:", problems)
else:
    # 1) Compile a snippet and capture its deterministic cache key.
    r = cython.compile_and_load_result("def f(int n):\n    return n*n\n", profile="fast-debug", verbose=0)
    key = r.key

    print("\nBuildResult:")
    print("  module_name:", r.module_name)
    print("  key        :", r.key)
    print("  artifact   :", r.artifact_path)
    print("  used_cache :", r.used_cache)

    # 2) List cache entries (safe if empty).
    entries = cython.list_cached()
    _print_entry_summary(entries)

    # Optional: cache stats snapshot (if available).
    if hasattr(cython, "cache_stats"):
        print("\nCache stats snapshot:")
        print(cython.cache_stats())

    # 3) Import the same module by key (restart-safe mechanism).
    # Use import_cached_result if available so we can inspect metadata.
    if hasattr(cython, "import_cached_result"):
        r2 = cython.import_cached_result(key)
        m2 = r2.module
        print("\nImported from cache (result API):")
        print("  module_name:", r2.module_name)
        print("  used_cache :", r2.used_cache)
        print("  artifact   :", r2.artifact_path)
    else:
        m2 = cython.import_cached(key)
        print("\nImported from cache (module API):", m2.__name__)

    # 4) Verify correctness strictly.
    out = m2.f(11)
    print("import_cached(key).f(11) =", out)
    print("Expected:", 121)
    print("Correct:", out == 121)
BuildResult:
  module_name: scikitplot_cython_c71820fcbdd3d3be
  key        : c71820fcbdd3d3be311db100faa9f7ce550548267112a935bc644a9c9e59e29d
  artifact   : /home/circleci/.cache/scikitplot/cython/c71820fcbdd3d3be311db100faa9f7ce550548267112a935bc644a9c9e59e29d/scikitplot_cython_c71820fcbdd3d3be.cpython-311-x86_64-linux-gnu.so
  used_cache : True
Cache entries: 5
Last 5 entries:
  - key: 093729e666d9308a2ee01f667576da3e7022aaf802855405f2fe6727629b9a2a
    module_name: scikitplot_cython_093729e666d9308a
    artifact_path: /home/circleci/.cache/scikitplot/cython/093729e666d9308a2ee01f667576da3e7022aaf802855405f2fe6727629b9a2a/scikitplot_cython_093729e666d9308a.cpython-311-x86_64-linux-gnu.so
    created_utc: 2026-02-01T06:33:52Z
  - key: 106892295832cfc7f01dbb65bd06b364352040aef37075f2634c508019b279d1
    module_name: scikitplot_cython_106892295832cfc7
    artifact_path: /home/circleci/.cache/scikitplot/cython/106892295832cfc7f01dbb65bd06b364352040aef37075f2634c508019b279d1/scikitplot_cython_106892295832cfc7.cpython-311-x86_64-linux-gnu.so
    created_utc: 2026-02-01T06:33:53Z
  - key: 632e06e9a1a7a87769ae8f9e448b50fa2865f5211a9c7fac72db477b95832e8d
    module_name: scikitplot_cython_632e06e9a1a7a877
    artifact_path: /home/circleci/.cache/scikitplot/cython/632e06e9a1a7a87769ae8f9e448b50fa2865f5211a9c7fac72db477b95832e8d/scikitplot_cython_632e06e9a1a7a877.cpython-311-x86_64-linux-gnu.so
    created_utc: 2026-02-01T06:33:52Z
  - key: b89f3272eca6106c5e5079f8fd5b949ad4898c3afd6de5904de4096323a5e9fb
    module_name: scikitplot_cython_b89f3272eca6106c
    artifact_path: /home/circleci/.cache/scikitplot/cython/b89f3272eca6106c5e5079f8fd5b949ad4898c3afd6de5904de4096323a5e9fb/scikitplot_cython_b89f3272eca6106c.cpython-311-x86_64-linux-gnu.so
    created_utc: 2026-02-01T06:33:54Z
  - key: c71820fcbdd3d3be311db100faa9f7ce550548267112a935bc644a9c9e59e29d
    module_name: scikitplot_cython_c71820fcbdd3d3be
    artifact_path: /home/circleci/.cache/scikitplot/cython/c71820fcbdd3d3be311db100faa9f7ce550548267112a935bc644a9c9e59e29d/scikitplot_cython_c71820fcbdd3d3be.cpython-311-x86_64-linux-gnu.so
    created_utc: 2026-02-01T06:33:52Z

Cache stats snapshot:
CacheStats(cache_root=PosixPath('/home/circleci/.cache/scikitplot/cython'), n_modules=6, n_packages=0, total_bytes=3757231, pinned_aliases=1, pinned_keys=1, newest_mtime_utc='2026-02-01T06:33:54Z', oldest_mtime_utc='2026-02-01T06:33:52Z')

Imported from cache (result API):
  module_name: scikitplot_cython_c71820fcbdd3d3be
  used_cache : True
  artifact   : /home/circleci/.cache/scikitplot/cython/c71820fcbdd3d3be311db100faa9f7ce550548267112a935bc644a9c9e59e29d/scikitplot_cython_c71820fcbdd3d3be.cpython-311-x86_64-linux-gnu.so
import_cached(key).f(11) = 121
Expected: 121
Correct: True

Tags: domain: cython plot-type: cython purpose: showcase

Total running time of the script: (0 minutes 0.009 seconds)

Related examples

Cython quickstart: compile_and_load

Cython quickstart: compile_and_load

Multi-module package builds (5 package examples)

Multi-module package builds (5 package examples)

Browse and compile templates

Browse and compile templates

Workflow templates (train / hpo / predict) + CLI entry template

Workflow templates (train / hpo / predict) + CLI entry template

Gallery generated by Sphinx-Gallery