python-ranges
raw JSON → 1.2.2 verified Mon Apr 27 auth: no python
Continuous Range, RangeSet, and RangeDict data structures for Python >=3.9. v1.2.2 provides immutable and hashable interval/multi-interval containers with O(log n) operations. Moderate release cadence.
pip install python-ranges Common errors
error ValueError: Cannot create Range with start > end ↓
cause Attempting to create Range(5, 1) where start > end.
fix
Ensure start <= end, e.g., Range(1, 5).
error TypeError: unhashable type: 'slice' ↓
cause Using slice objects (e.g., my_dict[1:5]) when Range objects are expected.
fix
Replace slice with Range: my_dict[Range(1, 5)].
Warnings
breaking Ranges are half-open [start, end) by default. Mistaking inclusive/exclusive leads to off-by-one errors. ↓
fix Remember that Range(a, b) includes a but excludes b. Use Range.closed(a, b) for inclusive endpoints if needed.
gotcha Range objects are immutable and hashable, but creation with invalid bounds (start > end) raises ValueError. ↓
fix Always validate that start <= end before constructing a Range.
gotcha When using RangeDict, keys must be Range objects; plain tuples or integers will not work and may raise TypeError or silently misbehave. ↓
fix Always use Range objects as keys in RangeDict.
Imports
- Range
from ranges import Range - RangeSet
from ranges import RangeSet - RangeDict
from ranges import RangeDict
Quickstart
from ranges import Range, RangeSet, RangeDict
# Create a Range
r = Range(1, 5) # [1, 5)
print(r) # Range(1, 5)
# Check membership
print(3 in r) # True
print(5 in r) # False
# Intersection, union
r2 = Range(3, 7) # [3, 7)
print(r & r2) # Range(3, 5)
print(r | r2) # RangeSet(Range(1, 7))
# RangeSet
rs = RangeSet(r, Range(10, 15))
print(rs) # RangeSet(Range(1, 5), Range(10, 15))
# RangeDict
rd = RangeDict({Range(0, 10): 'low', Range(10, 20): 'high'})
print(rd[5]) # 'low'