Collections Module¶
The rite.collections module provides advanced data structures including caches, buffers, trees, and collection utilities.
Overview¶
collections ¶
Collections Module¶
Comprehensive data structures and utilities for common programming patterns, organized into semantic submodules.
Submodules¶
- list: List manipulation (unique, flatten, chunk, group, partition)
- dict: Dictionary operations (merge, filter, invert, deep access)
- set: Set operations (union, intersection, difference)
- buffer: Ring buffers, circular buffers, and sliding windows
- cache: LRU, LFU, and TTL caches
- queue: Priority queues, circular queues, and deque wrappers
- tree: Tree nodes, binary trees, tries, and nested sets
- pattern: Design patterns (singleton, observer, object pool)
Examples¶
from rite.collections import list_unique, dict_merge list_unique([1, 2, 2, 3]) [1, 2, 3] dict_merge({"a": 1}, {"b": 2})
from rite.collections import CircularBuffer, LRUCache buf = CircularBuffer(5) cache = LRUCache(100)
Classes¶
BinaryTreeNode ¶
BinaryTreeNode Class¶
A binary tree node with left and right children.
Parameters¶
value : Any The value stored in this node. left : BinaryTreeNode | None Left child node. right : BinaryTreeNode | None Right child node.
Initialize a binary tree node.
value: The value to store.
left: Left child node.
right: Right child node.
Functions¶
has_left_child ¶
Check if node has left child.
bool: True if left child exists.
has_right_child ¶
Check if node has right child.
bool: True if right child exists.
inorder_traversal ¶
Perform in-order traversal (left, root, right).
list[Any]: Values in in-order.
postorder_traversal ¶
Perform post-order traversal (left, right, root).
list[Any]: Values in post-order.
preorder_traversal ¶
Perform pre-order traversal (root, left, right).
list[Any]: Values in pre-order.
traverse_inorder ¶
Alias for inorder_traversal for compatibility.
traverse_postorder ¶
Alias for postorder_traversal for compatibility.
traverse_preorder ¶
Alias for preorder_traversal for compatibility.
BoundedBuffer ¶
BoundedBuffer Class¶
A size-limited buffer that prevents overflow with configurable behavior.
Parameters¶
maxsize : int Maximum number of elements the buffer can hold. overflow_strategy : str Strategy when full: 'block', 'drop_oldest', 'drop_newest', 'raise'
Initialize the bounded buffer.
maxsize: Maximum capacity of the buffer.
overflow_strategy: Behavior when buffer is full.
CircularBuffer ¶
CircularBuffer Class¶
A fixed-size buffer that overwrites the oldest data when full.
Attributes¶
size : int The maximum number of elements the buffer can hold. buffer : list[Any | None] The internal list storing buffer elements. index : int The current index for the next write operation. full : bool Indicates if the buffer has reached its maximum capacity.
Methods¶
append(value: Any) -> None: Adds a value to the buffer, overwriting the oldest element if full. get_all() -> list[Any | None]: Retrieves all elements in the buffer in the correct order. is_empty() -> bool: Checks if the buffer is empty. is_full() -> bool: Checks if the buffer is full.
Initializes a CircularBuffer instance.
Parameters:¶
size : int The maximum number of elements the buffer can hold.
Functions¶
append ¶
Adds a value to the buffer. Overwrites the oldest element if the buffer is full.
Parameters:¶
value : Any The value to add to the buffer.
get_all ¶
Retrieves all elements in the buffer in the correct order.
Returns¶
list[Any | None]: A list of elements in the buffer, ordered from the oldest to the newest.
is_empty ¶
CircularQueue ¶
DequeWrapper ¶
LFUCache ¶
LFUCache Class¶
A Least Frequently Used (LFU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LFU cache.
capacity: Maximum cache size.
Functions¶
delete ¶
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
get ¶
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
put ¶
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
LRUCache ¶
LRUCache Class¶
A Least Recently Used (LRU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LRU cache.
capacity: Maximum cache size.
Functions¶
delete ¶
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
get ¶
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
items ¶
Get all key-value pairs.
list[tuple[Any, Any]]: List of (key, value) tuples.
put ¶
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
NestedSetStructure ¶
Nested Set Structure Class¶
A structure to track items and their hierarchical relationships. Supports multi-level trees with parent/child tracking. Useful for scenarios like recursive publishing, dependency resolution, or graph-like traversal.
Initialize the nested set structure.
Functions¶
add ¶
Add an item to the structure, optionally specifying a parent.
children ¶
Return the children of the given item. If the item has no children, returns an empty list.
nested_items ¶
Return a nested, flattened list of items (including children) in insertion order. Maintains hierarchy order.
original ¶
Return the original object stored in the set that equals item,
or item itself if not found. This is useful for matching
back to canonical instances.
parent ¶
Return the parent of the given item, or None if it has no parent.
ObjectPool ¶
ObjectPool(factory: Callable[[], Any], max_size: int = 10, reset: Callable[[Any], None] | None = None)
ObjectPool Class¶
A generic object pool for managing reusable objects.
Parameters¶
factory : Callable[[], Any] Factory function to create new objects. max_size : int Maximum number of objects in the pool. reset_func : Callable[[Any], None] | None Optional function to reset objects before reuse.
Initialize an object pool.
factory: Function to create new objects.
max_size: Maximum pool size.
reset_func: Optional function to reset objects.
Functions¶
acquire ¶
Acquire an object from the pool.
Any: An object from the pool or newly created.
available_count ¶
Get number of available objects.
int: Number of available objects.
in_use_count ¶
Get number of objects currently in use.
int: Number of in-use objects.
release ¶
Release an object back to the pool.
obj: The object to release.
ValueError: If object was not acquired from this pool.
size ¶
Get total number of objects managed by pool.
int: Total objects (available + in use).
Observable ¶
Observable Class¶
Base class for observable objects in the Observer pattern.
Initialize an observable object.
Observer ¶
PriorityQueue ¶
PriorityQueue Class¶
A priority queue where items with lower priority values are dequeued first.
Initialize an empty priority queue.
SingletonMeta ¶
Bases: type
SingletonMeta Class¶
A metaclass for implementing the Singleton pattern. This ensures that only one instance of a class exists throughout the application lifecycle.
Attributes¶
_instances : dict[type, Any] A dictionary that maps classes to their single instances.
Methods¶
call(*args, **kwargs):
Overrides the __call__ method to control instance creation.
Example¶
# Define a Singleton class
class Configuration(metaclass=SingletonMeta):
def __init__(self, value):
self.value = value
SlidingWindow ¶
SlidingWindow Class¶
A fixed-size window that slides over a data stream, useful for moving averages, rolling calculations, and stream processing.
Parameters¶
size : int The size of the sliding window. aggregation_func : Callable | None Optional function to apply to window contents.
Initialize the sliding window.
size: Window size (number of elements).
aggregation_func: Optional function to aggregate window data.
Functions¶
add ¶
Add a value to the window and return aggregated result.
value: The value to add to the window.
Any | None: Aggregated result if aggregation_func is set.
get_aggregate ¶
Get aggregated value of current window.
Any | None: Aggregated result or None if no aggregation function.
get_window ¶
Get current window contents.
list[Any]: Current window values in order.
moving_average ¶
Calculate moving average of numeric window.
float | None: Average of window values or None if empty.
moving_max ¶
Get maximum value in window.
Any | None: Maximum value or None if empty.
moving_min ¶
Get minimum value in window.
Any | None: Minimum value or None if empty.
moving_sum ¶
Calculate moving sum of numeric window.
float | None: Sum of window values or None if empty.
TTLCache ¶
TTLCache Class¶
A cache with Time-To-Live (TTL) expiration for entries.
Parameters¶
default_ttl : float Default time-to-live in seconds. max_size : int | None Optional maximum cache size.
Initialize a TTL cache.
default_ttl: Default expiration time in seconds.
max_size: Optional maximum cache size.
Functions¶
delete ¶
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
get ¶
Get a value from cache if not expired.
key: The key to look up.
Any | None: The value or None if not found/expired.
get_ttl ¶
Get remaining TTL for a key.
key: The key to check.
float | None: Remaining seconds or None if not found/expired.
put ¶
Add or update a key-value pair with TTL.
key: The key to store.
value: The value to store.
ttl: Optional TTL in seconds (uses default if not provided).
TreeNode ¶
TreeNode Class¶
A generic tree node that can have multiple children.
Parameters¶
value : Any The value stored in this node. children : list[TreeNode] | None Optional list of child nodes.
Initialize a tree node.
value: The value to store in this node.
children: Optional list of child nodes.
Functions¶
get_ancestors ¶
Get all ancestor nodes from parent to root.
list[TreeNode]: List of ancestors in order (parent to root).
get_depth ¶
Get the depth of this node (distance from root).
int: Depth of node (root is 0).
get_height ¶
Get the height of the subtree rooted at this node.
int: Height of subtree (leaf is 0).
get_siblings ¶
Get all sibling nodes (nodes with same parent).
list[TreeNode]: List of sibling nodes.
is_leaf ¶
Check if this node is a leaf (has no children).
bool: True if node has no children.
is_root ¶
Check if this node is a root (has no parent).
bool: True if node has no parent.
remove_child ¶
Remove a child node.
child: The child node to remove.
bool: True if child was removed, False if not found.
traverse_levelorder ¶
Traverse tree in level-order (breadth-first).
list[TreeNode]: Nodes in level-order.
traverse_postorder ¶
Traverse tree in post-order (children, then root).
list[TreeNode]: Nodes in post-order.
traverse_preorder ¶
Traverse tree in pre-order (root, then children).
list[TreeNode]: Nodes in pre-order.
Trie ¶
Trie Class¶
A prefix tree (trie) for efficient string operations like autocomplete, spell checking, and prefix matching.
Initialize an empty trie.
Functions¶
delete ¶
Delete a word from the trie.
word: The word to delete.
bool: True if word was deleted, False if not found.
get ¶
Get the value associated with a word.
word: The word to look up.
Any | None: Associated value or None if not found.
get_all_words ¶
Get all words stored in the trie.
list[str]: All words in the trie.
get_words_with_prefix ¶
Get all words that start with given prefix.
prefix: The prefix to match.
list[str]: List of words with the prefix.
insert ¶
Insert a word into the trie.
word: The word to insert.
value: Optional value to associate with the word.
search ¶
Search for an exact word in the trie.
word: The word to search for.
bool: True if word exists in trie.
starts_with ¶
Check if any word in trie starts with given prefix.
prefix: The prefix to check.
bool: True if prefix exists in trie.
Functions¶
set_difference ¶
set_intersection ¶
set_symmetric_difference ¶
set_union ¶
Modules¶
buffer ¶
Buffer Collections Module¶
Provides various buffer data structures for specialized data storage patterns.
Classes:¶
- CircularBuffer: Ring buffer with automatic overwriting
- RingBuffer: Alias for CircularBuffer
- BoundedBuffer: Size-limited buffer with overflow protection
- SlidingWindow: Moving window over a data stream
Classes¶
BoundedBuffer ¶
BoundedBuffer Class¶
A size-limited buffer that prevents overflow with configurable behavior.
Parameters¶
maxsize : int Maximum number of elements the buffer can hold. overflow_strategy : str Strategy when full: 'block', 'drop_oldest', 'drop_newest', 'raise'
Initialize the bounded buffer.
maxsize: Maximum capacity of the buffer.
overflow_strategy: Behavior when buffer is full.
CircularBuffer ¶
CircularBuffer Class¶
A fixed-size buffer that overwrites the oldest data when full.
Attributes¶
size : int The maximum number of elements the buffer can hold. buffer : list[Any | None] The internal list storing buffer elements. index : int The current index for the next write operation. full : bool Indicates if the buffer has reached its maximum capacity.
Methods¶
append(value: Any) -> None: Adds a value to the buffer, overwriting the oldest element if full. get_all() -> list[Any | None]: Retrieves all elements in the buffer in the correct order. is_empty() -> bool: Checks if the buffer is empty. is_full() -> bool: Checks if the buffer is full.
Initializes a CircularBuffer instance.
Parameters:¶
size : int The maximum number of elements the buffer can hold.
Adds a value to the buffer. Overwrites the oldest element if the buffer is full.
Parameters:¶
value : Any The value to add to the buffer.
Retrieves all elements in the buffer in the correct order.
Returns¶
list[Any | None]: A list of elements in the buffer, ordered from the oldest to the newest.
SlidingWindow ¶
SlidingWindow Class¶
A fixed-size window that slides over a data stream, useful for moving averages, rolling calculations, and stream processing.
Parameters¶
size : int The size of the sliding window. aggregation_func : Callable | None Optional function to apply to window contents.
Initialize the sliding window.
size: Window size (number of elements).
aggregation_func: Optional function to aggregate window data.
Add a value to the window and return aggregated result.
value: The value to add to the window.
Any | None: Aggregated result if aggregation_func is set.
Get aggregated value of current window.
Any | None: Aggregated result or None if no aggregation function.
Get current window contents.
list[Any]: Current window values in order.
Calculate moving average of numeric window.
float | None: Average of window values or None if empty.
Get maximum value in window.
Any | None: Maximum value or None if empty.
Get minimum value in window.
Any | None: Minimum value or None if empty.
Calculate moving sum of numeric window.
float | None: Sum of window values or None if empty.
Modules¶
bounded_buffer ¶
Bounded Buffer¶
A thread-safe bounded buffer that blocks or raises errors when capacity limits are reached.
BoundedBuffer Class¶
A size-limited buffer that prevents overflow with configurable behavior.
Parameters¶
maxsize : int Maximum number of elements the buffer can hold. overflow_strategy : str Strategy when full: 'block', 'drop_oldest', 'drop_newest', 'raise'
Initialize the bounded buffer.
maxsize: Maximum capacity of the buffer.
overflow_strategy: Behavior when buffer is full.
circular_buffer ¶
Circular Buffer¶
A circular buffer (ring buffer) implementation that overwrites the oldest entries when the buffer reaches its maximum capacity.
Classes:¶
- CircularBuffer: A fixed-size buffer with circular indexing.
Features:¶
- Append new elements, overwriting the oldest if the buffer is full.
- Retrieve all elements in the correct order.
- Check if the buffer is empty or full.
Usage:¶
buffer = CircularBuffer(size=5)
buffer.append(1)
buffer.append(2)
print(buffer.get_all()) # Outputs: [1, 2]
buffer.append(3)
buffer.append(4)
buffer.append(5)
print(buffer.get_all()) # Outputs: [1, 2, 3, 4, 5]
buffer.append(6)
print(buffer.get_all()) # Outputs: [6, 2, 3, 4, 5]
CircularBuffer Class¶
A fixed-size buffer that overwrites the oldest data when full.
Attributes¶
size : int The maximum number of elements the buffer can hold. buffer : list[Any | None] The internal list storing buffer elements. index : int The current index for the next write operation. full : bool Indicates if the buffer has reached its maximum capacity.
Methods¶
append(value: Any) -> None: Adds a value to the buffer, overwriting the oldest element if full. get_all() -> list[Any | None]: Retrieves all elements in the buffer in the correct order. is_empty() -> bool: Checks if the buffer is empty. is_full() -> bool: Checks if the buffer is full.
Initializes a CircularBuffer instance.
Parameters:¶
size : int The maximum number of elements the buffer can hold.
Adds a value to the buffer. Overwrites the oldest element if the buffer is full.
Parameters:¶
value : Any The value to add to the buffer.
Retrieves all elements in the buffer in the correct order.
Returns¶
list[Any | None]: A list of elements in the buffer, ordered from the oldest to the newest.
sliding_window ¶
Sliding Window¶
A sliding window data structure for stream processing and moving calculations.
SlidingWindow Class¶
A fixed-size window that slides over a data stream, useful for moving averages, rolling calculations, and stream processing.
Parameters¶
size : int The size of the sliding window. aggregation_func : Callable | None Optional function to apply to window contents.
Initialize the sliding window.
size: Window size (number of elements).
aggregation_func: Optional function to aggregate window data.
Add a value to the window and return aggregated result.
value: The value to add to the window.
Any | None: Aggregated result if aggregation_func is set.
Get aggregated value of current window.
Any | None: Aggregated result or None if no aggregation function.
Get current window contents.
list[Any]: Current window values in order.
Calculate moving average of numeric window.
float | None: Average of window values or None if empty.
Get maximum value in window.
Any | None: Maximum value or None if empty.
Get minimum value in window.
Any | None: Minimum value or None if empty.
Calculate moving sum of numeric window.
float | None: Sum of window values or None if empty.
cache ¶
Cache Collections Module¶
Provides caching data structures with various eviction policies.
Classes:¶
- LRUCache: Least Recently Used cache
- LFUCache: Least Frequently Used cache
- TTLCache: Time-To-Live cache
Classes¶
LFUCache ¶
LFUCache Class¶
A Least Frequently Used (LFU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LFU cache.
capacity: Maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
LRUCache ¶
LRUCache Class¶
A Least Recently Used (LRU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LRU cache.
capacity: Maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
Get all key-value pairs.
list[tuple[Any, Any]]: List of (key, value) tuples.
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
TTLCache ¶
TTLCache Class¶
A cache with Time-To-Live (TTL) expiration for entries.
Parameters¶
default_ttl : float Default time-to-live in seconds. max_size : int | None Optional maximum cache size.
Initialize a TTL cache.
default_ttl: Default expiration time in seconds.
max_size: Optional maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache if not expired.
key: The key to look up.
Any | None: The value or None if not found/expired.
Get remaining TTL for a key.
key: The key to check.
float | None: Remaining seconds or None if not found/expired.
Add or update a key-value pair with TTL.
key: The key to store.
value: The value to store.
ttl: Optional TTL in seconds (uses default if not provided).
Modules¶
lfu_cache ¶
LFU Cache¶
Least Frequently Used (LFU) cache implementation.
LFUCache Class¶
A Least Frequently Used (LFU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LFU cache.
capacity: Maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
lru_cache ¶
LRU Cache¶
Least Recently Used (LRU) cache implementation.
LRUCache Class¶
A Least Recently Used (LRU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LRU cache.
capacity: Maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
Get all key-value pairs.
list[tuple[Any, Any]]: List of (key, value) tuples.
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
ttl_cache ¶
TTL Cache¶
Time-To-Live (TTL) cache with automatic expiration.
TTLCache Class¶
A cache with Time-To-Live (TTL) expiration for entries.
Parameters¶
default_ttl : float Default time-to-live in seconds. max_size : int | None Optional maximum cache size.
Initialize a TTL cache.
default_ttl: Default expiration time in seconds.
max_size: Optional maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache if not expired.
key: The key to look up.
Any | None: The value or None if not found/expired.
Get remaining TTL for a key.
key: The key to check.
float | None: Remaining seconds or None if not found/expired.
Add or update a key-value pair with TTL.
key: The key to store.
value: The value to store.
ttl: Optional TTL in seconds (uses default if not provided).
dict ¶
Dictionary Operations Module¶
Utilities for dictionary manipulation and transformation.
Functions¶
- dict_merge: Merge multiple dictionaries.
- dict_filter: Filter dictionary by predicate.
- dict_invert: Swap keys and values.
- dict_deep_get: Get nested value safely.
- dict_deep_set: Set nested value, creating paths.
Examples¶
from rite.collections.dict import dict_merge, dict_filter dict_merge({"a": 1}, {"b": 2}) {'a': 1, 'b': 2} dict_filter({"a": 1, "b": 2}, lambda k, v: v > 1)
Modules¶
dict_deep_get ¶
Dict Deep Get¶
Safely get nested dictionary values using key paths.
Functions¶
- dict_deep_get: Get nested value using list of keys.
Examples¶
from rite.collections.dict import dict_deep_get data = {"user": {"profile": {"name": "John"}}} dict_deep_get(data, ["user", "profile", "name"]) 'John'
Get nested dictionary value using key path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[str, Any]
|
Dictionary to traverse. |
required |
keys
|
list[str]
|
List of keys forming path to desired value. |
required |
default
|
Any
|
Value to return if path doesn't exist. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Value at the key path or default. |
Examples:
dict_deep_set ¶
Dict Deep Set¶
Set nested dictionary values, creating intermediate dicts as needed.
Functions¶
- dict_deep_set: Set value at nested key path.
Examples¶
from rite.collections.dict import dict_deep_set d = {} dict_deep_set(d, ["user", "profile", "name"], "John") d {'user': {'profile': {'name': 'John'}}}
Set nested dictionary value, creating intermediate dicts.
Modifies dictionary in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[str, Any]
|
Dictionary to modify. |
required |
keys
|
list[str]
|
List of keys forming path where value should be set. |
required |
value
|
Any
|
Value to set at the key path. |
required |
Examples:
dict_filter ¶
Dict Filter¶
Filter dictionary entries based on key or value predicates.
Functions¶
- dict_filter: Filter dictionary by predicate.
Examples¶
from rite.collections.dict import dict_filter dict_filter({"a": 1, "b": 2, "c": 3}, lambda k, v: v > 1)
Filter dictionary entries based on predicate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[K, V]
|
Dictionary to filter. |
required |
predicate
|
Callable[[K, V], bool]
|
Function taking (key, value) returning True to keep. |
required |
Returns:
| Type | Description |
|---|---|
dict[K, V]
|
New dictionary with filtered entries. |
Examples:
dict_invert ¶
Dict Invert¶
Invert dictionary keys and values.
Functions¶
- dict_invert: Swap dictionary keys and values.
Examples¶
from rite.collections.dict import dict_invert dict_invert({"a": 1, "b": 2})
dict_merge ¶
Dict Merge¶
Merge multiple dictionaries with various strategies.
Functions¶
- dict_merge: Merge dictionaries with configurable behavior.
Examples¶
from rite.collections.dict import dict_merge dict_merge({"a": 1, "b": 2}, {"b": 3, "c": 4})
Merge multiple dictionaries.
Later dictionaries override earlier ones for duplicate keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*dicts
|
dict[K, V]
|
Variable number of dictionaries to merge. |
()
|
deep
|
bool
|
If True, recursively merge nested dicts. |
False
|
Returns:
| Type | Description |
|---|---|
dict[K, V]
|
New merged dictionary. |
Examples:
dict_deep_get ¶
Dict Deep Get¶
Safely get nested dictionary values using key paths.
Functions¶
- dict_deep_get: Get nested value using list of keys.
Examples¶
from rite.collections.dict import dict_deep_get data = {"user": {"profile": {"name": "John"}}} dict_deep_get(data, ["user", "profile", "name"]) 'John'
Functions¶
dict_deep_get ¶
Get nested dictionary value using key path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[str, Any]
|
Dictionary to traverse. |
required |
keys
|
list[str]
|
List of keys forming path to desired value. |
required |
default
|
Any
|
Value to return if path doesn't exist. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Value at the key path or default. |
Examples:
dict_deep_set ¶
Dict Deep Set¶
Set nested dictionary values, creating intermediate dicts as needed.
Functions¶
- dict_deep_set: Set value at nested key path.
Examples¶
from rite.collections.dict import dict_deep_set d = {} dict_deep_set(d, ["user", "profile", "name"], "John") d {'user': {'profile': {'name': 'John'}}}
Functions¶
dict_deep_set ¶
Set nested dictionary value, creating intermediate dicts.
Modifies dictionary in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[str, Any]
|
Dictionary to modify. |
required |
keys
|
list[str]
|
List of keys forming path where value should be set. |
required |
value
|
Any
|
Value to set at the key path. |
required |
Examples:
dict_filter ¶
Dict Filter¶
Filter dictionary entries based on key or value predicates.
Functions¶
- dict_filter: Filter dictionary by predicate.
Examples¶
from rite.collections.dict import dict_filter dict_filter({"a": 1, "b": 2, "c": 3}, lambda k, v: v > 1)
Functions¶
dict_filter ¶
Filter dictionary entries based on predicate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[K, V]
|
Dictionary to filter. |
required |
predicate
|
Callable[[K, V], bool]
|
Function taking (key, value) returning True to keep. |
required |
Returns:
| Type | Description |
|---|---|
dict[K, V]
|
New dictionary with filtered entries. |
Examples:
dict_invert ¶
Dict Invert¶
Invert dictionary keys and values.
Functions¶
- dict_invert: Swap dictionary keys and values.
Examples¶
from rite.collections.dict import dict_invert dict_invert({"a": 1, "b": 2})
Functions¶
dict_merge ¶
Dict Merge¶
Merge multiple dictionaries with various strategies.
Functions¶
- dict_merge: Merge dictionaries with configurable behavior.
Examples¶
from rite.collections.dict import dict_merge dict_merge({"a": 1, "b": 2}, {"b": 3, "c": 4})
Functions¶
dict_merge ¶
Merge multiple dictionaries.
Later dictionaries override earlier ones for duplicate keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*dicts
|
dict[K, V]
|
Variable number of dictionaries to merge. |
()
|
deep
|
bool
|
If True, recursively merge nested dicts. |
False
|
Returns:
| Type | Description |
|---|---|
dict[K, V]
|
New merged dictionary. |
Examples:
list ¶
List Operations Module¶
Utilities for list manipulation and transformation.
Functions¶
- list_unique: Remove duplicates while preserving order.
- list_flatten: Flatten nested lists recursively.
- list_chunk: Split list into chunks.
- list_group_by: Group items by key function or attribute.
- list_partition: Split list into two based on predicate.
- list_interleave: Interleave multiple lists.
Examples¶
from rite.collections.list import list_unique, list_chunk list_unique([1, 2, 2, 3]) [1, 2, 3] list_chunk([1, 2, 3, 4, 5], size=2) [[1, 2], [3, 4], [5]]
Modules¶
list_chunk ¶
List Chunk¶
Split a list into chunks of specified size.
Functions¶
- list_chunk: Split list into smaller chunks.
Examples¶
from rite.collections.list import list_chunk list_chunk([1, 2, 3, 4, 5], size=2) [[1, 2], [3, 4], [5]] list_chunk([1, 2, 3, 4, 5, 6], size=3) [[1, 2, 3], [4, 5, 6]]
Split a list into chunks of specified size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List to split into chunks. |
required |
size
|
int
|
Size of each chunk. Must be positive. |
required |
Returns:
| Type | Description |
|---|---|
list[list[T]]
|
List of chunks, last chunk may be smaller. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If size is not positive. |
Examples:
list_flatten ¶
List Flatten¶
Flatten nested lists into a single-level list.
Functions¶
- list_flatten: Flatten nested lists recursively.
Examples¶
from rite.collections.list import list_flatten list_flatten([[1, 2], [3, 4], [5]]) [1, 2, 3, 4, 5] list_flatten([[1, [2, 3]], [4, 5]]) [1, 2, 3, 4, 5]
list_group_by ¶
List Group By¶
Group list items by a key function or attribute.
Functions¶
- list_group_by: Group items by key.
Examples¶
from rite.collections.list import list_group_by data = [{"type": "fruit", "name": "apple"}] list_group_by(data, key="type") {'fruit': [{'type': 'fruit', 'name': 'apple'}]}
Group list items by a key function or dict key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List of items to group. |
required |
key
|
str | Callable[[T], K]
|
Either attribute name (str) or function to extract key. |
required |
Returns:
| Type | Description |
|---|---|
dict[Any, list[T]]
|
Dictionary mapping keys to lists of items. |
Examples:
list_interleave ¶
List Interleave¶
Interleave multiple lists together.
Functions¶
- list_interleave: Combine lists by alternating elements.
Examples¶
from rite.collections.list import list_interleave list_interleave([1, 2, 3], ['a', 'b', 'c']) [1, 'a', 2, 'b', 3, 'c']
list_partition ¶
List Partition¶
Partition a list into two lists based on a predicate function.
Functions¶
- list_partition: Split list into matching and non-matching items.
Examples¶
from rite.collections.list import list_partition list_partition([1, 2, 3, 4, 5], lambda x: x % 2 == 0) ([2, 4], [1, 3, 5])
Partition a list based on a predicate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List to partition. |
required |
predicate
|
Callable[[T], bool]
|
Function that returns True for items in first list. |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[T], list[T]]
|
Tuple of (matching_items, non_matching_items). |
Examples:
list_unique ¶
List Unique¶
Remove duplicate elements from a list while preserving order.
Functions¶
- list_unique: Remove duplicates from a list.
Examples¶
from rite.collections.list import list_unique list_unique([1, 2, 2, 3, 3, 3]) [1, 2, 3] list_unique(['a', 'b', 'a', 'c']) ['a', 'b', 'c']
Remove duplicate elements while preserving order.
Uses a set to track seen elements and preserves first occurrence of each unique element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List that may contain duplicates. |
required |
Returns:
| Type | Description |
|---|---|
list[T]
|
New list with duplicates removed, order preserved. |
Examples:
list_chunk ¶
List Chunk¶
Split a list into chunks of specified size.
Functions¶
- list_chunk: Split list into smaller chunks.
Examples¶
from rite.collections.list import list_chunk list_chunk([1, 2, 3, 4, 5], size=2) [[1, 2], [3, 4], [5]] list_chunk([1, 2, 3, 4, 5, 6], size=3) [[1, 2, 3], [4, 5, 6]]
Functions¶
list_chunk ¶
Split a list into chunks of specified size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List to split into chunks. |
required |
size
|
int
|
Size of each chunk. Must be positive. |
required |
Returns:
| Type | Description |
|---|---|
list[list[T]]
|
List of chunks, last chunk may be smaller. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If size is not positive. |
Examples:
list_flatten ¶
List Flatten¶
Flatten nested lists into a single-level list.
Functions¶
- list_flatten: Flatten nested lists recursively.
Examples¶
from rite.collections.list import list_flatten list_flatten([[1, 2], [3, 4], [5]]) [1, 2, 3, 4, 5] list_flatten([[1, [2, 3]], [4, 5]]) [1, 2, 3, 4, 5]
list_group_by ¶
List Group By¶
Group list items by a key function or attribute.
Functions¶
- list_group_by: Group items by key.
Examples¶
from rite.collections.list import list_group_by data = [{"type": "fruit", "name": "apple"}] list_group_by(data, key="type") {'fruit': [{'type': 'fruit', 'name': 'apple'}]}
Functions¶
list_group_by ¶
Group list items by a key function or dict key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List of items to group. |
required |
key
|
str | Callable[[T], K]
|
Either attribute name (str) or function to extract key. |
required |
Returns:
| Type | Description |
|---|---|
dict[Any, list[T]]
|
Dictionary mapping keys to lists of items. |
Examples:
list_interleave ¶
List Interleave¶
Interleave multiple lists together.
Functions¶
- list_interleave: Combine lists by alternating elements.
Examples¶
from rite.collections.list import list_interleave list_interleave([1, 2, 3], ['a', 'b', 'c']) [1, 'a', 2, 'b', 3, 'c']
list_partition ¶
List Partition¶
Partition a list into two lists based on a predicate function.
Functions¶
- list_partition: Split list into matching and non-matching items.
Examples¶
from rite.collections.list import list_partition list_partition([1, 2, 3, 4, 5], lambda x: x % 2 == 0) ([2, 4], [1, 3, 5])
Functions¶
list_partition ¶
Partition a list based on a predicate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List to partition. |
required |
predicate
|
Callable[[T], bool]
|
Function that returns True for items in first list. |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[T], list[T]]
|
Tuple of (matching_items, non_matching_items). |
Examples:
list_unique ¶
List Unique¶
Remove duplicate elements from a list while preserving order.
Functions¶
- list_unique: Remove duplicates from a list.
Examples¶
from rite.collections.list import list_unique list_unique([1, 2, 2, 3, 3, 3]) [1, 2, 3] list_unique(['a', 'b', 'a', 'c']) ['a', 'b', 'c']
Functions¶
list_unique ¶
Remove duplicate elements while preserving order.
Uses a set to track seen elements and preserves first occurrence of each unique element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List that may contain duplicates. |
required |
Returns:
| Type | Description |
|---|---|
list[T]
|
New list with duplicates removed, order preserved. |
Examples:
pattern ¶
Design Pattern Collections Module¶
Provides design pattern implementations for common software patterns.
Classes:¶
- SingletonMeta: Singleton pattern metaclass
- Observer: Observer pattern implementation
- ObjectPool: Object pool pattern
Classes¶
ObjectPool ¶
ObjectPool(factory: Callable[[], Any], max_size: int = 10, reset: Callable[[Any], None] | None = None)
ObjectPool Class¶
A generic object pool for managing reusable objects.
Parameters¶
factory : Callable[[], Any] Factory function to create new objects. max_size : int Maximum number of objects in the pool. reset_func : Callable[[Any], None] | None Optional function to reset objects before reuse.
Initialize an object pool.
factory: Function to create new objects.
max_size: Maximum pool size.
reset_func: Optional function to reset objects.
Acquire an object from the pool.
Any: An object from the pool or newly created.
Get number of available objects.
int: Number of available objects.
Get number of objects currently in use.
int: Number of in-use objects.
Release an object back to the pool.
obj: The object to release.
ValueError: If object was not acquired from this pool.
Get total number of objects managed by pool.
int: Total objects (available + in use).
Observable ¶
Observable Class¶
Base class for observable objects in the Observer pattern.
Initialize an observable object.
Observer ¶
SingletonMeta ¶
Bases: type
SingletonMeta Class¶
A metaclass for implementing the Singleton pattern. This ensures that only one instance of a class exists throughout the application lifecycle.
Attributes¶
_instances : dict[type, Any] A dictionary that maps classes to their single instances.
Methods¶
call(*args, **kwargs):
Overrides the __call__ method to control instance creation.
Example¶
# Define a Singleton class
class Configuration(metaclass=SingletonMeta):
def __init__(self, value):
self.value = value
Modules¶
object_pool ¶
Object Pool Pattern¶
Implementation of the Object Pool design pattern for resource management.
ObjectPool(factory: Callable[[], Any], max_size: int = 10, reset: Callable[[Any], None] | None = None)
ObjectPool Class¶
A generic object pool for managing reusable objects.
Parameters¶
factory : Callable[[], Any] Factory function to create new objects. max_size : int Maximum number of objects in the pool. reset_func : Callable[[Any], None] | None Optional function to reset objects before reuse.
Initialize an object pool.
factory: Function to create new objects.
max_size: Maximum pool size.
reset_func: Optional function to reset objects.
Acquire an object from the pool.
Any: An object from the pool or newly created.
Get number of available objects.
int: Number of available objects.
Get number of objects currently in use.
int: Number of in-use objects.
Release an object back to the pool.
obj: The object to release.
ValueError: If object was not acquired from this pool.
Get total number of objects managed by pool.
int: Total objects (available + in use).
observer ¶
Observer Pattern¶
Implementation of the Observer design pattern for event-driven programming.
Observable Class¶
Base class for observable objects in the Observer pattern.
Initialize an observable object.
singleton ¶
Singleton Module¶
This module provides a metaclass SingletonMeta for implementing the Singleton
design pattern. Classes using this metaclass ensure that only one instance of
the class is created, regardless of how many times it is instantiated.
Classes:¶
- SingletonMeta: A metaclass for implementing the Singleton pattern.
Features:¶
- Ensures a single instance of a class.
- Thread-safe by default.
- Provides an easy-to-use interface for creating Singleton classes.
Usage:¶
To use the Singleton pattern, define your class with SingletonMeta as its
metaclass:
class MySingleton(metaclass=SingletonMeta):
pass # pylint: disable=unnecessary-pass
Example:¶
# Define a Singleton class
class Configuration(metaclass=SingletonMeta):
def __init__(self, value):
self.value = value
# Test the Singleton behavior
config1 = Configuration("value1")
config2 = Configuration("value2")
assert config1 is config2 # True
print(config1.value) # Outputs: value2
Bases: type
SingletonMeta Class¶
A metaclass for implementing the Singleton pattern. This ensures that only one instance of a class exists throughout the application lifecycle.
Attributes¶
_instances : dict[type, Any] A dictionary that maps classes to their single instances.
Methods¶
call(*args, **kwargs):
Overrides the __call__ method to control instance creation.
Example¶
# Define a Singleton class
class Configuration(metaclass=SingletonMeta):
def __init__(self, value):
self.value = value
queue ¶
Queue Collections Module¶
Provides specialized queue implementations.
Classes:¶
- PriorityQueue: Priority-based queue
- DequeWrapper: Enhanced deque wrapper
- CircularQueue: Circular queue implementation
Classes¶
CircularQueue ¶
DequeWrapper ¶
PriorityQueue ¶
PriorityQueue Class¶
A priority queue where items with lower priority values are dequeued first.
Initialize an empty priority queue.
Modules¶
circular_queue ¶
deque_wrapper ¶
Deque Wrapper¶
Enhanced deque wrapper with additional functionality.
priority_queue ¶
Priority Queue¶
A priority queue implementation using heapq.
PriorityQueue Class¶
A priority queue where items with lower priority values are dequeued first.
Initialize an empty priority queue.
set ¶
Set Operations Module¶
Utilities for set operations and transformations.
Functions¶
- set_union: Union of multiple sets.
- set_intersection: Intersection of multiple sets.
- set_difference: Difference of sets.
- set_symmetric_difference: Symmetric difference of two sets.
Examples¶
from rite.collections.set import set_union set_union({1, 2}, {2, 3}, {3, 4})
Functions¶
set_difference ¶
set_intersection ¶
set_symmetric_difference ¶
set_union ¶
tree ¶
Tree Collections Module¶
Provides tree data structures and hierarchical data management.
Classes:¶
- NestedSetStructure: Hierarchical parent-child relationship manager
- TreeNode: Generic tree node with children
- BinaryTreeNode: Binary tree node implementation
- Trie: Prefix tree for string operations
Classes¶
BinaryTreeNode ¶
BinaryTreeNode Class¶
A binary tree node with left and right children.
Parameters¶
value : Any The value stored in this node. left : BinaryTreeNode | None Left child node. right : BinaryTreeNode | None Right child node.
Initialize a binary tree node.
value: The value to store.
left: Left child node.
right: Right child node.
Check if node has left child.
bool: True if left child exists.
Check if node has right child.
bool: True if right child exists.
Perform in-order traversal (left, root, right).
list[Any]: Values in in-order.
Perform post-order traversal (left, right, root).
list[Any]: Values in post-order.
Perform pre-order traversal (root, left, right).
list[Any]: Values in pre-order.
Alias for inorder_traversal for compatibility.
Alias for postorder_traversal for compatibility.
Alias for preorder_traversal for compatibility.
NestedSetStructure ¶
Nested Set Structure Class¶
A structure to track items and their hierarchical relationships. Supports multi-level trees with parent/child tracking. Useful for scenarios like recursive publishing, dependency resolution, or graph-like traversal.
Initialize the nested set structure.
Add an item to the structure, optionally specifying a parent.
Return the children of the given item. If the item has no children, returns an empty list.
Return a nested, flattened list of items (including children) in insertion order. Maintains hierarchy order.
Return the original object stored in the set that equals item,
or item itself if not found. This is useful for matching
back to canonical instances.
Return the parent of the given item, or None if it has no parent.
TreeNode ¶
TreeNode Class¶
A generic tree node that can have multiple children.
Parameters¶
value : Any The value stored in this node. children : list[TreeNode] | None Optional list of child nodes.
Initialize a tree node.
value: The value to store in this node.
children: Optional list of child nodes.
Get all ancestor nodes from parent to root.
list[TreeNode]: List of ancestors in order (parent to root).
Get the depth of this node (distance from root).
int: Depth of node (root is 0).
Get the height of the subtree rooted at this node.
int: Height of subtree (leaf is 0).
Get all sibling nodes (nodes with same parent).
list[TreeNode]: List of sibling nodes.
Check if this node is a leaf (has no children).
bool: True if node has no children.
Check if this node is a root (has no parent).
bool: True if node has no parent.
Remove a child node.
child: The child node to remove.
bool: True if child was removed, False if not found.
Traverse tree in level-order (breadth-first).
list[TreeNode]: Nodes in level-order.
Traverse tree in post-order (children, then root).
list[TreeNode]: Nodes in post-order.
Traverse tree in pre-order (root, then children).
list[TreeNode]: Nodes in pre-order.
Trie ¶
Trie Class¶
A prefix tree (trie) for efficient string operations like autocomplete, spell checking, and prefix matching.
Initialize an empty trie.
Delete a word from the trie.
word: The word to delete.
bool: True if word was deleted, False if not found.
Get the value associated with a word.
word: The word to look up.
Any | None: Associated value or None if not found.
Get all words stored in the trie.
list[str]: All words in the trie.
Get all words that start with given prefix.
prefix: The prefix to match.
list[str]: List of words with the prefix.
Insert a word into the trie.
word: The word to insert.
value: Optional value to associate with the word.
Search for an exact word in the trie.
word: The word to search for.
bool: True if word exists in trie.
Check if any word in trie starts with given prefix.
prefix: The prefix to check.
bool: True if prefix exists in trie.
Modules¶
binary_tree_node ¶
Binary Tree Node¶
Binary tree node with left and right children.
BinaryTreeNode Class¶
A binary tree node with left and right children.
Parameters¶
value : Any The value stored in this node. left : BinaryTreeNode | None Left child node. right : BinaryTreeNode | None Right child node.
Initialize a binary tree node.
value: The value to store.
left: Left child node.
right: Right child node.
Check if node has left child.
bool: True if left child exists.
Check if node has right child.
bool: True if right child exists.
Perform in-order traversal (left, root, right).
list[Any]: Values in in-order.
Perform post-order traversal (left, right, root).
list[Any]: Values in post-order.
Perform pre-order traversal (root, left, right).
list[Any]: Values in pre-order.
Alias for inorder_traversal for compatibility.
Alias for postorder_traversal for compatibility.
Alias for preorder_traversal for compatibility.
nested_set ¶
Nested Set Structure Module¶
This module provides a NestedSetStructure class that allows for the
management of hierarchical relationships between items. It supports
adding items with parent-child relationships, retrieving children and parents,
and provides a way to retrieve all items in a nested, flattened order.
Nested Set Structure Class¶
A structure to track items and their hierarchical relationships. Supports multi-level trees with parent/child tracking. Useful for scenarios like recursive publishing, dependency resolution, or graph-like traversal.
Initialize the nested set structure.
Add an item to the structure, optionally specifying a parent.
Return the children of the given item. If the item has no children, returns an empty list.
Return a nested, flattened list of items (including children) in insertion order. Maintains hierarchy order.
Return the original object stored in the set that equals item,
or item itself if not found. This is useful for matching
back to canonical instances.
Return the parent of the given item, or None if it has no parent.
tree_node ¶
Tree Node¶
Generic tree node implementation with children and parent tracking.
TreeNode Class¶
A generic tree node that can have multiple children.
Parameters¶
value : Any The value stored in this node. children : list[TreeNode] | None Optional list of child nodes.
Initialize a tree node.
value: The value to store in this node.
children: Optional list of child nodes.
Get all ancestor nodes from parent to root.
list[TreeNode]: List of ancestors in order (parent to root).
Get the depth of this node (distance from root).
int: Depth of node (root is 0).
Get the height of the subtree rooted at this node.
int: Height of subtree (leaf is 0).
Get all sibling nodes (nodes with same parent).
list[TreeNode]: List of sibling nodes.
Check if this node is a leaf (has no children).
bool: True if node has no children.
Check if this node is a root (has no parent).
bool: True if node has no parent.
Remove a child node.
child: The child node to remove.
bool: True if child was removed, False if not found.
Traverse tree in level-order (breadth-first).
list[TreeNode]: Nodes in level-order.
Traverse tree in post-order (children, then root).
list[TreeNode]: Nodes in post-order.
Traverse tree in pre-order (root, then children).
list[TreeNode]: Nodes in pre-order.
trie ¶
Trie (Prefix Tree)¶
A trie data structure for efficient string prefix operations.
Trie Class¶
A prefix tree (trie) for efficient string operations like autocomplete, spell checking, and prefix matching.
Initialize an empty trie.
Delete a word from the trie.
word: The word to delete.
bool: True if word was deleted, False if not found.
Get the value associated with a word.
word: The word to look up.
Any | None: Associated value or None if not found.
Get all words stored in the trie.
list[str]: All words in the trie.
Get all words that start with given prefix.
prefix: The prefix to match.
list[str]: List of words with the prefix.
Insert a word into the trie.
word: The word to insert.
value: Optional value to associate with the word.
Search for an exact word in the trie.
word: The word to search for.
bool: True if word exists in trie.
Check if any word in trie starts with given prefix.
prefix: The prefix to check.
bool: True if prefix exists in trie.
Submodules¶
Cache¶
LRU, LFU, and TTL cache implementations.
Cache Collections Module¶
Provides caching data structures with various eviction policies.
Classes:¶
- LRUCache: Least Recently Used cache
- LFUCache: Least Frequently Used cache
- TTLCache: Time-To-Live cache
Modules¶
lru_cache ¶
LRU Cache¶
Least Recently Used (LRU) cache implementation.
Classes¶
LRUCache ¶
LRUCache Class¶
A Least Recently Used (LRU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LRU cache.
capacity: Maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
Get all key-value pairs.
list[tuple[Any, Any]]: List of (key, value) tuples.
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
lfu_cache ¶
LFU Cache¶
Least Frequently Used (LFU) cache implementation.
Classes¶
LFUCache ¶
LFUCache Class¶
A Least Frequently Used (LFU) cache with fixed capacity.
Parameters¶
capacity : int Maximum number of items to store in cache.
Initialize an LFU cache.
capacity: Maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache.
key: The key to look up.
Any | None: The value or None if not found.
Add or update a key-value pair in cache.
key: The key to store.
value: The value to store.
ttl_cache ¶
TTL Cache¶
Time-To-Live (TTL) cache with automatic expiration.
Classes¶
TTLCache ¶
TTLCache Class¶
A cache with Time-To-Live (TTL) expiration for entries.
Parameters¶
default_ttl : float Default time-to-live in seconds. max_size : int | None Optional maximum cache size.
Initialize a TTL cache.
default_ttl: Default expiration time in seconds.
max_size: Optional maximum cache size.
Delete a key from cache.
key: The key to delete.
bool: True if key was deleted, False if not found.
Get a value from cache if not expired.
key: The key to look up.
Any | None: The value or None if not found/expired.
Get remaining TTL for a key.
key: The key to check.
float | None: Remaining seconds or None if not found/expired.
Add or update a key-value pair with TTL.
key: The key to store.
value: The value to store.
ttl: Optional TTL in seconds (uses default if not provided).
Buffer¶
Circular and sliding window buffers.
Buffer Collections Module¶
Provides various buffer data structures for specialized data storage patterns.
Classes:¶
- CircularBuffer: Ring buffer with automatic overwriting
- RingBuffer: Alias for CircularBuffer
- BoundedBuffer: Size-limited buffer with overflow protection
- SlidingWindow: Moving window over a data stream
Modules¶
circular_buffer ¶
Circular Buffer¶
A circular buffer (ring buffer) implementation that overwrites the oldest entries when the buffer reaches its maximum capacity.
Classes:¶
- CircularBuffer: A fixed-size buffer with circular indexing.
Features:¶
- Append new elements, overwriting the oldest if the buffer is full.
- Retrieve all elements in the correct order.
- Check if the buffer is empty or full.
Usage:¶
buffer = CircularBuffer(size=5)
buffer.append(1)
buffer.append(2)
print(buffer.get_all()) # Outputs: [1, 2]
buffer.append(3)
buffer.append(4)
buffer.append(5)
print(buffer.get_all()) # Outputs: [1, 2, 3, 4, 5]
buffer.append(6)
print(buffer.get_all()) # Outputs: [6, 2, 3, 4, 5]
Classes¶
CircularBuffer ¶
CircularBuffer Class¶
A fixed-size buffer that overwrites the oldest data when full.
Attributes¶
size : int The maximum number of elements the buffer can hold. buffer : list[Any | None] The internal list storing buffer elements. index : int The current index for the next write operation. full : bool Indicates if the buffer has reached its maximum capacity.
Methods¶
append(value: Any) -> None: Adds a value to the buffer, overwriting the oldest element if full. get_all() -> list[Any | None]: Retrieves all elements in the buffer in the correct order. is_empty() -> bool: Checks if the buffer is empty. is_full() -> bool: Checks if the buffer is full.
Initializes a CircularBuffer instance.
Parameters:¶
size : int The maximum number of elements the buffer can hold.
Adds a value to the buffer. Overwrites the oldest element if the buffer is full.
Parameters:¶
value : Any The value to add to the buffer.
Retrieves all elements in the buffer in the correct order.
Returns¶
list[Any | None]: A list of elements in the buffer, ordered from the oldest to the newest.
bounded_buffer ¶
Bounded Buffer¶
A thread-safe bounded buffer that blocks or raises errors when capacity limits are reached.
Classes¶
BoundedBuffer ¶
BoundedBuffer Class¶
A size-limited buffer that prevents overflow with configurable behavior.
Parameters¶
maxsize : int Maximum number of elements the buffer can hold. overflow_strategy : str Strategy when full: 'block', 'drop_oldest', 'drop_newest', 'raise'
Initialize the bounded buffer.
maxsize: Maximum capacity of the buffer.
overflow_strategy: Behavior when buffer is full.
sliding_window ¶
Sliding Window¶
A sliding window data structure for stream processing and moving calculations.
Classes¶
SlidingWindow ¶
SlidingWindow Class¶
A fixed-size window that slides over a data stream, useful for moving averages, rolling calculations, and stream processing.
Parameters¶
size : int The size of the sliding window. aggregation_func : Callable | None Optional function to apply to window contents.
Initialize the sliding window.
size: Window size (number of elements).
aggregation_func: Optional function to aggregate window data.
Add a value to the window and return aggregated result.
value: The value to add to the window.
Any | None: Aggregated result if aggregation_func is set.
Get aggregated value of current window.
Any | None: Aggregated result or None if no aggregation function.
Get current window contents.
list[Any]: Current window values in order.
Calculate moving average of numeric window.
float | None: Average of window values or None if empty.
Get maximum value in window.
Any | None: Maximum value or None if empty.
Get minimum value in window.
Any | None: Minimum value or None if empty.
Calculate moving sum of numeric window.
float | None: Sum of window values or None if empty.
Dictionary Utilities¶
Deep operations on dictionaries.
Dictionary Operations Module¶
Utilities for dictionary manipulation and transformation.
Functions¶
- dict_merge: Merge multiple dictionaries.
- dict_filter: Filter dictionary by predicate.
- dict_invert: Swap keys and values.
- dict_deep_get: Get nested value safely.
- dict_deep_set: Set nested value, creating paths.
Examples¶
from rite.collections.dict import dict_merge, dict_filter dict_merge({"a": 1}, {"b": 2}) {'a': 1, 'b': 2} dict_filter({"a": 1, "b": 2}, lambda k, v: v > 1)
Modules¶
dict_deep_get ¶
Dict Deep Get¶
Safely get nested dictionary values using key paths.
Functions¶
- dict_deep_get: Get nested value using list of keys.
Examples¶
from rite.collections.dict import dict_deep_get data = {"user": {"profile": {"name": "John"}}} dict_deep_get(data, ["user", "profile", "name"]) 'John'
Functions¶
dict_deep_get ¶
Get nested dictionary value using key path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[str, Any]
|
Dictionary to traverse. |
required |
keys
|
list[str]
|
List of keys forming path to desired value. |
required |
default
|
Any
|
Value to return if path doesn't exist. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Value at the key path or default. |
Examples:
dict_deep_set ¶
Dict Deep Set¶
Set nested dictionary values, creating intermediate dicts as needed.
Functions¶
- dict_deep_set: Set value at nested key path.
Examples¶
from rite.collections.dict import dict_deep_set d = {} dict_deep_set(d, ["user", "profile", "name"], "John") d {'user': {'profile': {'name': 'John'}}}
Functions¶
dict_deep_set ¶
Set nested dictionary value, creating intermediate dicts.
Modifies dictionary in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[str, Any]
|
Dictionary to modify. |
required |
keys
|
list[str]
|
List of keys forming path where value should be set. |
required |
value
|
Any
|
Value to set at the key path. |
required |
Examples:
dict_merge ¶
Dict Merge¶
Merge multiple dictionaries with various strategies.
Functions¶
- dict_merge: Merge dictionaries with configurable behavior.
Examples¶
from rite.collections.dict import dict_merge dict_merge({"a": 1, "b": 2}, {"b": 3, "c": 4})
Functions¶
dict_merge ¶
Merge multiple dictionaries.
Later dictionaries override earlier ones for duplicate keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*dicts
|
dict[K, V]
|
Variable number of dictionaries to merge. |
()
|
deep
|
bool
|
If True, recursively merge nested dicts. |
False
|
Returns:
| Type | Description |
|---|---|
dict[K, V]
|
New merged dictionary. |
Examples:
dict_filter ¶
Dict Filter¶
Filter dictionary entries based on key or value predicates.
Functions¶
- dict_filter: Filter dictionary by predicate.
Examples¶
from rite.collections.dict import dict_filter dict_filter({"a": 1, "b": 2, "c": 3}, lambda k, v: v > 1)
Functions¶
dict_filter ¶
Filter dictionary entries based on predicate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict[K, V]
|
Dictionary to filter. |
required |
predicate
|
Callable[[K, V], bool]
|
Function taking (key, value) returning True to keep. |
required |
Returns:
| Type | Description |
|---|---|
dict[K, V]
|
New dictionary with filtered entries. |
Examples:
dict_invert ¶
Dict Invert¶
Invert dictionary keys and values.
Functions¶
- dict_invert: Swap dictionary keys and values.
Examples¶
from rite.collections.dict import dict_invert dict_invert({"a": 1, "b": 2})
Functions¶
List Utilities¶
Advanced list operations.
List Operations Module¶
Utilities for list manipulation and transformation.
Functions¶
- list_unique: Remove duplicates while preserving order.
- list_flatten: Flatten nested lists recursively.
- list_chunk: Split list into chunks.
- list_group_by: Group items by key function or attribute.
- list_partition: Split list into two based on predicate.
- list_interleave: Interleave multiple lists.
Examples¶
from rite.collections.list import list_unique, list_chunk list_unique([1, 2, 2, 3]) [1, 2, 3] list_chunk([1, 2, 3, 4, 5], size=2) [[1, 2], [3, 4], [5]]
Modules¶
list_chunk ¶
List Chunk¶
Split a list into chunks of specified size.
Functions¶
- list_chunk: Split list into smaller chunks.
Examples¶
from rite.collections.list import list_chunk list_chunk([1, 2, 3, 4, 5], size=2) [[1, 2], [3, 4], [5]] list_chunk([1, 2, 3, 4, 5, 6], size=3) [[1, 2, 3], [4, 5, 6]]
Functions¶
list_chunk ¶
Split a list into chunks of specified size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List to split into chunks. |
required |
size
|
int
|
Size of each chunk. Must be positive. |
required |
Returns:
| Type | Description |
|---|---|
list[list[T]]
|
List of chunks, last chunk may be smaller. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If size is not positive. |
Examples:
list_flatten ¶
List Flatten¶
Flatten nested lists into a single-level list.
Functions¶
- list_flatten: Flatten nested lists recursively.
Examples¶
from rite.collections.list import list_flatten list_flatten([[1, 2], [3, 4], [5]]) [1, 2, 3, 4, 5] list_flatten([[1, [2, 3]], [4, 5]]) [1, 2, 3, 4, 5]
list_group_by ¶
List Group By¶
Group list items by a key function or attribute.
Functions¶
- list_group_by: Group items by key.
Examples¶
from rite.collections.list import list_group_by data = [{"type": "fruit", "name": "apple"}] list_group_by(data, key="type") {'fruit': [{'type': 'fruit', 'name': 'apple'}]}
Functions¶
list_group_by ¶
Group list items by a key function or dict key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List of items to group. |
required |
key
|
str | Callable[[T], K]
|
Either attribute name (str) or function to extract key. |
required |
Returns:
| Type | Description |
|---|---|
dict[Any, list[T]]
|
Dictionary mapping keys to lists of items. |
Examples:
list_interleave ¶
List Interleave¶
Interleave multiple lists together.
Functions¶
- list_interleave: Combine lists by alternating elements.
Examples¶
from rite.collections.list import list_interleave list_interleave([1, 2, 3], ['a', 'b', 'c']) [1, 'a', 2, 'b', 3, 'c']
list_partition ¶
List Partition¶
Partition a list into two lists based on a predicate function.
Functions¶
- list_partition: Split list into matching and non-matching items.
Examples¶
from rite.collections.list import list_partition list_partition([1, 2, 3, 4, 5], lambda x: x % 2 == 0) ([2, 4], [1, 3, 5])
Functions¶
list_partition ¶
Partition a list based on a predicate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List to partition. |
required |
predicate
|
Callable[[T], bool]
|
Function that returns True for items in first list. |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[T], list[T]]
|
Tuple of (matching_items, non_matching_items). |
Examples:
list_unique ¶
List Unique¶
Remove duplicate elements from a list while preserving order.
Functions¶
- list_unique: Remove duplicates from a list.
Examples¶
from rite.collections.list import list_unique list_unique([1, 2, 2, 3, 3, 3]) [1, 2, 3] list_unique(['a', 'b', 'a', 'c']) ['a', 'b', 'c']
Functions¶
list_unique ¶
Remove duplicate elements while preserving order.
Uses a set to track seen elements and preserves first occurrence of each unique element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[T]
|
List that may contain duplicates. |
required |
Returns:
| Type | Description |
|---|---|
list[T]
|
New list with duplicates removed, order preserved. |
Examples:
Tree Structures¶
Tree and trie data structures.
Tree Collections Module¶
Provides tree data structures and hierarchical data management.
Classes:¶
- NestedSetStructure: Hierarchical parent-child relationship manager
- TreeNode: Generic tree node with children
- BinaryTreeNode: Binary tree node implementation
- Trie: Prefix tree for string operations
Classes¶
TreeNode ¶
TreeNode Class¶
A generic tree node that can have multiple children.
Parameters¶
value : Any The value stored in this node. children : list[TreeNode] | None Optional list of child nodes.
Initialize a tree node.
value: The value to store in this node.
children: Optional list of child nodes.
Functions¶
get_ancestors ¶
Get all ancestor nodes from parent to root.
list[TreeNode]: List of ancestors in order (parent to root).
get_depth ¶
Get the depth of this node (distance from root).
int: Depth of node (root is 0).
get_height ¶
Get the height of the subtree rooted at this node.
int: Height of subtree (leaf is 0).
get_siblings ¶
Get all sibling nodes (nodes with same parent).
list[TreeNode]: List of sibling nodes.
is_leaf ¶
Check if this node is a leaf (has no children).
bool: True if node has no children.
is_root ¶
Check if this node is a root (has no parent).
bool: True if node has no parent.
remove_child ¶
Remove a child node.
child: The child node to remove.
bool: True if child was removed, False if not found.
traverse_levelorder ¶
Traverse tree in level-order (breadth-first).
list[TreeNode]: Nodes in level-order.
traverse_postorder ¶
Traverse tree in post-order (children, then root).
list[TreeNode]: Nodes in post-order.
traverse_preorder ¶
Traverse tree in pre-order (root, then children).
list[TreeNode]: Nodes in pre-order.
BinaryTreeNode ¶
BinaryTreeNode Class¶
A binary tree node with left and right children.
Parameters¶
value : Any The value stored in this node. left : BinaryTreeNode | None Left child node. right : BinaryTreeNode | None Right child node.
Initialize a binary tree node.
value: The value to store.
left: Left child node.
right: Right child node.
Functions¶
has_left_child ¶
Check if node has left child.
bool: True if left child exists.
has_right_child ¶
Check if node has right child.
bool: True if right child exists.
inorder_traversal ¶
Perform in-order traversal (left, root, right).
list[Any]: Values in in-order.
postorder_traversal ¶
Perform post-order traversal (left, right, root).
list[Any]: Values in post-order.
preorder_traversal ¶
Perform pre-order traversal (root, left, right).
list[Any]: Values in pre-order.
traverse_inorder ¶
Alias for inorder_traversal for compatibility.
traverse_postorder ¶
Alias for postorder_traversal for compatibility.
traverse_preorder ¶
Alias for preorder_traversal for compatibility.
Trie ¶
Trie Class¶
A prefix tree (trie) for efficient string operations like autocomplete, spell checking, and prefix matching.
Initialize an empty trie.
Functions¶
delete ¶
Delete a word from the trie.
word: The word to delete.
bool: True if word was deleted, False if not found.
get ¶
Get the value associated with a word.
word: The word to look up.
Any | None: Associated value or None if not found.
get_all_words ¶
Get all words stored in the trie.
list[str]: All words in the trie.
get_words_with_prefix ¶
Get all words that start with given prefix.
prefix: The prefix to match.
list[str]: List of words with the prefix.
insert ¶
Insert a word into the trie.
word: The word to insert.
value: Optional value to associate with the word.
search ¶
Search for an exact word in the trie.
word: The word to search for.
bool: True if word exists in trie.
starts_with ¶
Check if any word in trie starts with given prefix.
prefix: The prefix to check.
bool: True if prefix exists in trie.
Examples¶
from rite.collections import (
lru_cache,
circular_buffer,
dict_deep_get,
list_chunk
)
# LRU Cache
cache = lru_cache(maxsize=100)
# Circular Buffer
buffer = circular_buffer(capacity=10)
buffer.append(1)
buffer.append(2)
# Deep dictionary access
data = {"a": {"b": {"c": 42}}}
value = dict_deep_get(data, ["a", "b", "c"]) # 42
# Chunk list
items = [1, 2, 3, 4, 5, 6]
chunks = list_chunk(items, 2) # [[1, 2], [3, 4], [5, 6]]