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. This way, the CircularDict will be always up-to-date with the last N added elements, ensuring that neither the maximum length nor the memory usage limit is exceeded. It is ideal for caching large data structures while maintaining control over memory footprint.
Slowing down. Last release over 2 years ago, little activity since. Fine for existing code; think twice for a new project.
pip install circular-dictCircularDict
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.
Built 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 and scalable solution for various use cases.
Installation
To install CircularDict simply run:
pip install circular-dict
Usage
Working 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.
from circular_dict import CircularDict
# Initialize a CircularDict with a maximum length of 3 items and a storage limit of 4Mb
my_dict = CircularDict(maxlen=3, maxsize_bytes=4*1024*1024)
Example with maxlen
You can use maxlen to define the maximum amount of items that the dictionary can store. It is useful for defining fixed size buffers.
from circular_dict import CircularDict
# Initialize a CircularDict with a maximum length of 3
my_buffer = CircularDict(maxlen=3)
# Fill it with 3 items
my_buffer['item1'] = 'value1'
my_buffer['item2'] = 'value2'
my_buffer['item3'] = 'value3'
print(f"When filling it: {circ_dict}")
# Add another item
my_buffer['item4'] = 'value4'
print(f"After adding an element beyond maxlen: {circ_dict}")
Output:
When filling it: {'item1': 'value1', 'item2': 'value2', 'item3': 'value3'}
After adding an element beyond maxlen: {'item2': 'value2', 'item3': 'value3', 'item4': 'value4'}