{"id":18511987,"url":"https://github.com/eric-canas/circulardict","last_synced_at":"2025-04-09T05:33:03.425Z","repository":{"id":182497569,"uuid":"655678441","full_name":"Eric-Canas/CircularDict","owner":"Eric-Canas","description":"CircularDict is a high-performance Python data structure that blends the functionality of dictionaries and circular buffers. Inheriting the usage of traditional dictionaries, it allows you to define constraints on size and memory usage. Ideal for caching large data structures while maintaining control over memory footprint.","archived":false,"fork":false,"pushed_at":"2024-05-13T06:06:39.000Z","size":124,"stargazers_count":8,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-09T04:29:56.089Z","etag":null,"topics":["buffer","circular-buffer","circular-queue","dict","dictionary","memory-management","utility"],"latest_commit_sha":null,"homepage":"https://github.com/Eric-Canas/CircularDict","language":"Python","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/Eric-Canas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","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},"funding":{"github":"Eric-Canas"}},"created_at":"2023-06-19T11:28:03.000Z","updated_at":"2025-01-07T05:13:53.000Z","dependencies_parsed_at":"2024-11-06T15:51:34.221Z","dependency_job_id":null,"html_url":"https://github.com/Eric-Canas/CircularDict","commit_stats":null,"previous_names":["eric-canas/circulardict"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Eric-Canas%2FCircularDict","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Eric-Canas%2FCircularDict/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Eric-Canas%2FCircularDict/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Eric-Canas%2FCircularDict/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Eric-Canas","download_url":"https://codeload.github.com/Eric-Canas/CircularDict/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247987057,"owners_count":21028891,"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":["buffer","circular-buffer","circular-queue","dict","dictionary","memory-management","utility"],"created_at":"2024-11-06T15:31:19.723Z","updated_at":"2025-04-09T05:32:58.412Z","avatar_url":"https://github.com/Eric-Canas.png","language":"Python","funding_links":["https://github.com/sponsors/Eric-Canas"],"categories":[],"sub_categories":[],"readme":"# CircularDict\n\u003cimg alt=\"CircularDict\" title=\"CircularDict\" src=\"https://raw.githubusercontent.com/Eric-Canas/CircularDict/main/resources/logo.png\" width=\"20%\" align=\"left\"\u003e **CircularDict** is a Python `dict` that acts as a **Circular Buffer**. This dictionary maintains a **controlled size**, limited either by a specified **number of items** (_maxlen_) or **total size in bytes** (_maxsize_bytes_). Upon reaching the defined limit, **CircularDict** automatically removes the oldest entries, maintaining **memory usage** under control.\n\nBuilt upon Python's `OrderedDict`, **CircularDict** inherits all **standard dictionary usage** and operations, augmented by the capability of **memory management**. It's particularly useful in scenarios such as **caching**, where limiting **memory consumption** is crucial. The class combines _dictionary_ and _circular-queue_ behaviors, providing an efficient, scalable and thread safe solution for various use cases.\n\n## Installation\n\nTo install **CircularDict** simply run:\n\n```bash\npip install circular-dict\n```\n\n## Usage\n\nWorking with **CircularDict** is as simple as using a standard Python `dict`, with additional parameters `maxlen` or `maxsize_bytes` on the initialization to control the buffer size. You can use one of them or both.\n```python\nfrom circular_dict import CircularDict\n# Initialize a CircularDict with a maximum length of 3 items and a storage limit of 4Mb\nmy_dict = CircularDict(maxlen=3, maxsize_bytes=4*1024*1024)\n```\n\n### Example with `maxlen`\nYou can use `maxlen` to define the maximum amount of items that the dictionary can store. It is useful for defining fixed size buffers.\n\n```python\nfrom circular_dict import CircularDict\n\n# Initialize a CircularDict with a maximum length of 3\nmy_buffer = CircularDict(maxlen=3)\n\n# Fill it with 3 items\nmy_buffer['item1'] = 'value1'\nmy_buffer['item2'] = 'value2'\nmy_buffer['item3'] = 'value3'\n\nprint(f\"When filling it: {circ_dict}\")\n\n# Add another item\nmy_buffer['item4'] = 'value4'\n\nprint(f\"After adding an element beyond maxlen: {circ_dict}\")\n```\n\nOutput:\n```bash\nWhen filling it: {'item1': 'value1', 'item2': 'value2', 'item3': 'value3'}\nAfter adding an element beyond maxlen: {'item2': 'value2', 'item3': 'value3', 'item4': 'value4'}\n```\n\n### Example with `maxsize_bytes`\nYou can use `maxsize_bytes` to define the maximum amount of memory that the `dict` can store. It is particularly beneficial when defining **caches**, to prevent **memory overflows**.\n\n```python\nfrom circular_dict import CircularDict\nimport numpy as np\nimport sys\n\n# Initialize a CircularDict with a maximum length of 100KB\nmy_buffer = CircularDict(maxsize_bytes=100*1024)\n\n# Add two arrays of ~40Kb (10*1024*4 bytes (int32) + 5 bytes (chars) + 100 bytes (numpy structure) + 50 bytes (str structure))\nmy_buffer['item1'] = np.zeros((10, 1024), dtype=np.int32)\nmy_buffer['item2'] = np.ones((10, 1024), dtype=np.int32)\n\nprint(f\"{len(my_buffer)} Elements {tuple(my_buffer.keys())}. Dict size: {my_buffer.current_size/1024} Kb\")\n\n# Add a new element of ~32Kb will delete oldest elements ('item1') until fitting in the `dict`.\nmy_buffer['item3'] = np.ones((8, 1024), dtype=np.int32)\n\nprint(f\"{len(my_buffer)} Elements {tuple(my_buffer.keys())}. Dict size: {my_buffer.current_size/1024} Kb\")\n\n# Create an element of ~160Kb (bigger than the defined maximum storage) to trigger a MemoryError\ntoo_big_array = np.ones((40, 1024), dtype=np.int32)\ntry:\n  # Try to add it to the dict\n  my_buffer['item4'] = too_big_array\nexcept MemoryError:\n  print(f\"Cannot add an element with {sys.getsizeof(too_big_array)/1024}Kb in a dict with\"\\\n        f\"maxsize_bytes of {my_buffer.maxsize_bytes/1024} Kb. Current elements {tuple(my_buffer.keys())}\")\n```\n\nOutput\n\n```bash\n2 Elements ('item1', 'item2'). Dict size: 80.35 Kb\n2 Elements ('item2', 'item3'). Dict size: 72.35 Kb\nCannot add an element with 160.12Kb in a dict with maxsize_bytes of 100.0 Kb. Current elements ('item2', 'item3')\n```\n\nPlease remember that the `maxsize_bytes` parameter considers the **total** memory footprint, including the sizes of _keys_ and _values_. If you try to add an item that exceeds the `maxsize_bytes`, a `MemoryError` will be raised. \n\nIn environments like [PyPy](https://www.pypy.org/) where [`sys.getsizeof()` is not available](https://doc.pypy.org/en/latest/cpython_differences.html#miscellaneous) `maxsize_bytes` cannot be used and must be setted to `None`.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feric-canas%2Fcirculardict","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feric-canas%2Fcirculardict","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feric-canas%2Fcirculardict/lists"}