{"id":13813880,"url":"https://github.com/explosion/cymem","last_synced_at":"2025-12-18T00:10:50.532Z","repository":{"id":20874729,"uuid":"24161806","full_name":"explosion/cymem","owner":"explosion","description":"💥  Cython memory pool for RAII-style memory management","archived":false,"fork":false,"pushed_at":"2025-01-16T20:57:08.000Z","size":181,"stargazers_count":453,"open_issues_count":1,"forks_count":28,"subscribers_count":23,"default_branch":"master","last_synced_at":"2025-04-10T01:05:08.214Z","etag":null,"topics":["cython","python"],"latest_commit_sha":null,"homepage":"","language":"Cython","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/explosion.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-09-17T20:46:50.000Z","updated_at":"2025-04-04T04:04:21.000Z","dependencies_parsed_at":"2023-01-13T21:11:22.601Z","dependency_job_id":"5b79a6bc-416e-469f-99c3-eb7d3a70846c","html_url":"https://github.com/explosion/cymem","commit_stats":{"total_commits":195,"total_committers":9,"mean_commits":"21.666666666666668","dds":0.676923076923077,"last_synced_commit":"5d63d0e226a3e9796bd537654a3b2d9d9a47bd58"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/explosion%2Fcymem","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/explosion%2Fcymem/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/explosion%2Fcymem/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/explosion%2Fcymem/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/explosion","download_url":"https://codeload.github.com/explosion/cymem/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254042311,"owners_count":22004898,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cython","python"],"created_at":"2024-08-04T04:01:34.308Z","updated_at":"2025-12-18T00:10:50.489Z","avatar_url":"https://github.com/explosion.png","language":"Cython","readme":"\u003ca href=\"https://explosion.ai\"\u003e\u003cimg src=\"https://explosion.ai/assets/img/logo.svg\" width=\"125\" height=\"125\" align=\"right\" /\u003e\u003c/a\u003e\n\n# cymem: A Cython Memory Helper\n\ncymem provides two small memory-management helpers for Cython. They make it easy\nto tie memory to a Python object's life-cycle, so that the memory is freed when\nthe object is garbage collected.\n\n[![tests](https://github.com/explosion/cymem/actions/workflows/tests.yml/badge.svg)](https://github.com/explosion/cymem/actions/workflows/tests.yml)\n[![pypi Version](https://img.shields.io/pypi/v/cymem.svg?style=flat-square\u0026logo=pypi\u0026logoColor=white)](https://pypi.python.org/pypi/cymem)\n[![conda Version](https://img.shields.io/conda/vn/conda-forge/cymem.svg?style=flat-square\u0026logo=conda-forge\u0026logoColor=white)](https://anaconda.org/conda-forge/cymem)\n[![Python wheels](https://img.shields.io/badge/wheels-%E2%9C%93-4c1.svg?longCache=true\u0026style=flat-square\u0026logo=python\u0026logoColor=white)](https://github.com/explosion/wheelwright/releases)\n\n## Overview\n\nThe most useful is `cymem.Pool`, which acts as a thin wrapper around the calloc\nfunction:\n\n```python\nfrom cymem.cymem cimport Pool\ncdef Pool mem = Pool()\ndata1 = \u003cint*\u003emem.alloc(10, sizeof(int))\ndata2 = \u003cfloat*\u003emem.alloc(12, sizeof(float))\n```\n\nThe `Pool` object saves the memory addresses internally, and frees them when the\nobject is garbage collected. Typically you'll attach the `Pool` to some cdef'd\nclass. This is particularly handy for deeply nested structs, which have\ncomplicated initialization functions. Just pass the `Pool` object into the\ninitializer, and you don't have to worry about freeing your struct at all — all\nof the calls to `Pool.alloc` will be automatically freed when the `Pool`\nexpires.\n\n## Installation\n\nInstallation is via [pip](https://pypi.python.org/pypi/pip), and requires\n[Cython](http://cython.org). Before installing, make sure that your `pip`,\n`setuptools` and `wheel` are up to date.\n\n```bash\npip install -U pip setuptools wheel\npip install cymem\n```\n\n## Example Use Case: An array of structs\n\nLet's say we want a sequence of sparse matrices. We need fast access, and a\nPython list isn't performing well enough. So, we want a C-array or C++ vector,\nwhich means we need the sparse matrix to be a C-level struct — it can't be a\nPython class. We can write this easily enough in Cython:\n\n```python\n\"\"\"Example without Cymem\n\nTo use an array of structs, we must carefully walk the data structure when\nwe deallocate it.\n\"\"\"\n\nfrom libc.stdlib cimport calloc, free\n\ncdef struct SparseRow:\n    size_t length\n    size_t* indices\n    double* values\n\ncdef struct SparseMatrix:\n    size_t length\n    SparseRow* rows\n\ncdef class MatrixArray:\n    cdef size_t length\n    cdef SparseMatrix** matrices\n\n    def __cinit__(self, list py_matrices):\n        self.length = 0\n        self.matrices = NULL\n\n    def __init__(self, list py_matrices):\n        self.length = len(py_matrices)\n        self.matrices = \u003cSparseMatrix**\u003ecalloc(len(py_matrices), sizeof(SparseMatrix*))\n\n        for i, py_matrix in enumerate(py_matrices):\n            self.matrices[i] = sparse_matrix_init(py_matrix)\n\n    def __dealloc__(self):\n        for i in range(self.length):\n            sparse_matrix_free(self.matrices[i])\n        free(self.matrices)\n\n\ncdef SparseMatrix* sparse_matrix_init(list py_matrix) except NULL:\n    sm = \u003cSparseMatrix*\u003ecalloc(1, sizeof(SparseMatrix))\n    sm.length = len(py_matrix)\n    sm.rows = \u003cSparseRow*\u003ecalloc(sm.length, sizeof(SparseRow))\n    cdef size_t i, j\n    cdef dict py_row\n    cdef size_t idx\n    cdef double value\n    for i, py_row in enumerate(py_matrix):\n        sm.rows[i].length = len(py_row)\n        sm.rows[i].indices = \u003csize_t*\u003ecalloc(sm.rows[i].length, sizeof(size_t))\n        sm.rows[i].values = \u003cdouble*\u003ecalloc(sm.rows[i].length, sizeof(double))\n        for j, (idx, value) in enumerate(py_row.items()):\n            sm.rows[i].indices[j] = idx\n            sm.rows[i].values[j] = value\n    return sm\n\n\ncdef void* sparse_matrix_free(SparseMatrix* sm) except *:\n    cdef size_t i\n    for i in range(sm.length):\n        free(sm.rows[i].indices)\n        free(sm.rows[i].values)\n    free(sm.rows)\n    free(sm)\n```\n\nWe wrap the data structure in a Python ref-counted class at as low a level as we\ncan, given our performance constraints. This allows us to allocate and free the\nmemory in the `__cinit__` and `__dealloc__` Cython special methods.\n\nHowever, it's very easy to make mistakes when writing the `__dealloc__` and\n`sparse_matrix_free` functions, leading to memory leaks. cymem prevents you from\nwriting these deallocators at all. Instead, you write as follows:\n\n```python\n\"\"\"Example with Cymem.\n\nMemory allocation is hidden behind the Pool class, which remembers the\naddresses it gives out.  When the Pool object is garbage collected, all of\nits addresses are freed.\n\nWe don't need to write MatrixArray.__dealloc__ or sparse_matrix_free,\neliminating a common class of bugs.\n\"\"\"\nfrom cymem.cymem cimport Pool\n\ncdef struct SparseRow:\n    size_t length\n    size_t* indices\n    double* values\n\ncdef struct SparseMatrix:\n    size_t length\n    SparseRow* rows\n\n\ncdef class MatrixArray:\n    cdef size_t length\n    cdef SparseMatrix** matrices\n    cdef Pool mem\n\n    def __cinit__(self, list py_matrices):\n        self.mem = None\n        self.length = 0\n        self.matrices = NULL\n\n    def __init__(self, list py_matrices):\n        self.mem = Pool()\n        self.length = len(py_matrices)\n        self.matrices = \u003cSparseMatrix**\u003eself.mem.alloc(self.length, sizeof(SparseMatrix*))\n        for i, py_matrix in enumerate(py_matrices):\n            self.matrices[i] = sparse_matrix_init(self.mem, py_matrix)\n\ncdef SparseMatrix* sparse_matrix_init_cymem(Pool mem, list py_matrix) except NULL:\n    sm = \u003cSparseMatrix*\u003emem.alloc(1, sizeof(SparseMatrix))\n    sm.length = len(py_matrix)\n    sm.rows = \u003cSparseRow*\u003emem.alloc(sm.length, sizeof(SparseRow))\n    cdef size_t i, j\n    cdef dict py_row\n    cdef size_t idx\n    cdef double value\n    for i, py_row in enumerate(py_matrix):\n        sm.rows[i].length = len(py_row)\n        sm.rows[i].indices = \u003csize_t*\u003emem.alloc(sm.rows[i].length, sizeof(size_t))\n        sm.rows[i].values = \u003cdouble*\u003emem.alloc(sm.rows[i].length, sizeof(double))\n        for j, (idx, value) in enumerate(py_row.items()):\n            sm.rows[i].indices[j] = idx\n            sm.rows[i].values[j] = value\n    return sm\n```\n\nAll that the `Pool` class does is remember the addresses it gives out. When the\n`MatrixArray` object is garbage-collected, the `Pool` object will also be\ngarbage collected, which triggers a call to `Pool.__dealloc__`. The `Pool` then\nfrees all of its addresses. This saves you from walking back over your nested\ndata structures to free them, eliminating a common class of errors.\n\n## Custom Allocators\n\nSometimes external C libraries use private functions to allocate and free\nobjects, but we'd still like the laziness of the `Pool`.\n\n```python\nfrom cymem.cymem cimport Pool, WrapMalloc, WrapFree\ncdef Pool mem = Pool(WrapMalloc(priv_malloc), WrapFree(priv_free))\n```\n","funding_links":[],"categories":["Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexplosion%2Fcymem","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fexplosion%2Fcymem","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexplosion%2Fcymem/lists"}