jaraco-collections
jaraco.collections provides a suite of collection objects and utilities that complement Python's standard library `collections` module. It offers specialized data structures like `RangeMap`, `FrozenDict`, and `FoldedCaseKeyedDict`. The library is actively maintained, with its current version being 5.2.1, and releases occurring regularly.
Warnings
- breaking The `DictFilter` class was removed in version 5.0.0. Users upgrading from pre-5.0.0 versions should refactor their code to use alternative filtering mechanisms.
- gotcha When using `Projection`, it maintains a reference to the original dictionary. Modifying the original dictionary after creating a `Projection` will also affect the `Projection`'s view.
- gotcha The `RangeMap` implementation is inherently designed to be 'open-ended on one side' when defining ranges implicitly by sorted keys. Ensure your key definitions account for this behavior, especially at the boundaries.
- gotcha For users of multiple `jaraco.*` namespace packages (e.g., `jaraco.collections`, `jaraco.text`), significant changes in Python's namespace package handling (from `pkg_resources` to `pkgutil` to native namespace packages) can lead to import errors if not all `jaraco.*` packages are migrated or installed consistently.
Install
-
pip install jaraco-collections
Imports
- RangeMap
from jaraco.collections import RangeMap
- FrozenDict
from jaraco.collections import FrozenDict
- FoldedCaseKeyedDict
from jaraco.collections import FoldedCaseKeyedDict
- Projection
from jaraco.collections import Projection
Quickstart
from jaraco.collections import RangeMap
# Create a RangeMap to associate values with key ranges
price_tiers = RangeMap({(0, 50): 'economy', (51, 100): 'standard', (101, float('inf')): 'premium'})
# Retrieve values based on a key within a range
print(f"Price 30 is in the {price_tiers[30]} tier")
print(f"Price 75 is in the {price_tiers[75]} tier")
print(f"Price 120 is in the {price_tiers[120]} tier")
# Example of FrozenDict (immutable dictionary)
from jaraco.collections import FrozenDict
f_dict = FrozenDict({'a': 1, 'b': 2})
print(f"Frozen dict: {f_dict}")
# f_dict['c'] = 3 # This would raise a TypeError