cymem

2.0.13 · active · verified Sun Mar 29

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.

Warnings

Install

Imports

Quickstart

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.

from cymem.cymem cimport Pool
from libc.stdlib cimport sizeof

def main():
    cdef Pool mem = Pool()
    cdef int* data1 = <int*>mem.alloc(10, sizeof(int))
    cdef float* data2 = <float*>mem.alloc(12, sizeof(float))

    # Use data1 and data2
    data1[0] = 100
    data2[0] = 3.14

    print(f"Data1 at index 0: {data1[0]}")
    print(f"Data2 at index 0: {data2[0]}")

    # Memory is automatically freed when 'mem' (the Pool object) is garbage collected.
    # No explicit free() calls are needed for memory allocated via Pool.

# To run this, you would typically compile it with Cython:
# cython -3 --inplace your_module.pyx
# Then import and call main() from Python:
# import your_module
# your_module.main()

view raw JSON →