cymem is a Python library that provides efficient memory-management helpers for Cython. It simplifies tying C-level memory allocations (via `calloc`/`free`) to the lifecycle of Python objects, automatically freeing memory when the owning Python object is garbage collected. The core component is `cymem.Pool`, a thin wrapper around `calloc`. Currently at version 2.0.13, it maintains a regular release cadence, often aligning with new Python version support and performance enhancements like free-threading.
pip install cymemVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to allocate C-level memory using `cymem.Pool` within a Cython `.pyx` file. The `Pool` object handles the deallocation of all memory allocated through it when the `Pool` instance itself is garbage collected, simplifying memory management in Cython extensions.
Ensure critical sections are used for internal state access, and apply fine-grained locks or other synchronization primitives when sharing access to memory contents across threads. Do not rely on coarse-grained locks on the `Pool` instance itself for memory content synchronization.
Ensure your installed Cython version is compatible with the `cymem` version. If encountering this error, try recompiling your Cython project (if you're compiling `cymem` from source or an older wheel) or updating `cymem` to a version with wheels pre-built against a compatible Cython release. It's recommended to update `pip`, `setuptools`, and `wheel` before installing to ensure the latest compatible binary wheels are used.
Carefully manage the lifetime of your `cdef` Python objects that hold `cymem.Pool` instances. Ensure that any C pointers derived from the pool are only accessed while the owning Python object and its associated `Pool` are still alive and in scope.
If you are developing a Cython extension, ensure your source file is named `.pyx` and is compiled with Cython. If you intend to use `cymem` from Python, you typically import a *compiled* module that uses `cymem` internally, or `cymem`'s public Python API if available, using standard Python `import` statements. Do not use `cimport` in `.py` files.
Use `cimport` exclusively within Cython (`.pyx`) files. To use `cymem.Pool` from a Python (`.py`) file, import it like a regular Python object (e.g., `from cymem.cymem import Pool`) after the `cymem` library (or your own Cython code that `cimports` `cymem`) has been properly compiled and installed.