Complete worked example
python
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
def inspect_example(rows):
data = np.asarray(rows, dtype=np.float64)
if data.ndim != 2 or 0 in data.shape or not np.isfinite(data).all():
raise ValueError("expected a non-empty finite matrix")
with TemporaryDirectory(prefix="numpy-learning-") as directory:
path = Path(directory) / "measurements.npy"
np.save(path, data, allow_pickle=False)
loaded = np.load(path, allow_pickle=False)
if loaded.dtype != np.dtype("float64") or loaded.shape != data.shape:
raise ValueError("readback metadata changed")
return loaded.copy()- Reasoning
- The function constructs and validates the matrix before writing. Within TemporaryDirectory it chooses a fixed filename, calls np.save and np.load with non-pickle settings, and compares the loaded dtype and shape with the expected contract. The returned copy survives after the directory is cleaned up. The lab observes the actual load/save options as well as the returned numerical result. This is genuine file I/O in a computer lab, not a simulated success message in the reader. Closing the file and releasing the temporary directory are part of the resource lifetime. A memory-mapped array would introduce a different lifetime and platform behavior; it should not be returned from this example without additional ownership decisions.