A mutable, self-balancing interval tree data structure that enables efficient querying of intervals by point, range overlap, or range envelopment
—
The Interval class represents a half-open interval [begin, end) with optional data. Intervals are immutable namedtuples that provide comparison, overlap detection, and utility methods for working with ranges.
Create intervals from begin/end points with optional data payload.
class Interval:
def __new__(cls, begin, end, data=None):
"""
Create a new interval (namedtuple constructor).
Parameters:
- begin: Lower bound (inclusive) - any comparable type
- end: Upper bound (exclusive) - any comparable type
- data: Optional data payload - any type
Returns:
Interval object representing [begin, end)
"""Access interval boundaries and data.
# Properties (read-only)
begin: Any # Lower bound (inclusive)
end: Any # Upper bound (exclusive)
data: Any # Optional data payload (None if not provided)Test for overlaps between intervals, ranges, or points.
def overlaps(self, begin, end=None):
"""
Test whether interval overlaps with point, range, or another interval.
Parameters:
- begin: Point value, range start, or Interval object
- end: Range end (optional, only needed for range queries)
Returns:
bool: True if overlap exists, False otherwise
"""
def overlap_size(self, begin, end=None):
"""
Calculate the size of overlap between intervals or with a range.
Parameters:
- begin: Point value, range start, or Interval object
- end: Range end (optional, only needed for range queries)
Returns:
Number: Size of overlap, 0 if no overlap exists
"""Test point and interval containment relationships.
def contains_point(self, p):
"""
Test whether interval contains a point.
Parameters:
- p: Point to test (any comparable type)
Returns:
bool: True if begin <= p < end, False otherwise
"""
def contains_interval(self, other):
"""
Test whether this interval completely contains another interval.
Parameters:
- other: Interval to test for containment
Returns:
bool: True if other is completely contained, False otherwise
"""Standard comparison operations for sorting and ordering intervals.
def __eq__(self, other):
"""
Test equality including data field.
Parameters:
- other: Interval to compare
Returns:
bool: True if begin, end, and data all match
"""
def range_matches(self, other):
"""
Test whether ranges match (ignoring data field).
Parameters:
- other: Interval to compare
Returns:
bool: True if begin and end match, ignoring data
"""
def __hash__(self):
"""
Hash based on begin and end only (data ignored).
Returns:
int: Hash value suitable for use in sets and dicts
"""
def __lt__(self, other):
"""Less than comparison for sorting."""
def __gt__(self, other):
"""Greater than comparison for sorting."""Specialized comparison methods for interval positioning.
def lt(self, other):
"""
Test if strictly less than (no overlap).
Parameters:
- other: Interval or point to compare
Returns:
bool: True if this interval ends before other begins
Raises:
ValueError: If either interval is null
"""
def le(self, other):
"""
Test if less than or overlapping.
Parameters:
- other: Interval or point to compare
Returns:
bool: True if this interval doesn't extend past other's end
Raises:
ValueError: If either interval is null
"""
def gt(self, other):
"""
Test if strictly greater than (no overlap).
Parameters:
- other: Interval or point to compare
Returns:
bool: True if this interval begins after other ends
Raises:
ValueError: If either interval is null
"""
def ge(self, other):
"""
Test if greater than or overlapping.
Parameters:
- other: Interval or point to compare
Returns:
bool: True if this interval doesn't start before other
Raises:
ValueError: If either interval is null
"""Calculate distances and measurements between intervals.
def distance_to(self, other):
"""
Calculate distance between intervals or to a point.
Parameters:
- other: Interval or point
Returns:
Number: Distance between intervals (0 if overlapping)
"""
def length(self):
"""
Calculate interval length.
Returns:
Number: Length of interval (end - begin), 0 for null intervals
"""
def is_null(self):
"""
Test if interval is null (begin >= end).
Returns:
bool: True if interval is null, False otherwise
"""Copying and string representation methods.
def copy(self):
"""
Create shallow copy of interval.
Returns:
Interval: New interval with same begin, end, and data
"""
def __repr__(self):
"""
String representation suitable for eval().
Returns:
str: Executable string representation
"""
def __str__(self):
"""Alias for __repr__()."""from intervaltree import Interval
# Create intervals
i1 = Interval(0, 10, "first")
i2 = Interval(5, 15, "second")
i3 = Interval(20, 30)
# Test overlaps
print(i1.overlaps(i2)) # True
print(i1.overlaps(7)) # True (point overlap)
print(i1.overlaps(i3)) # False
# Calculate overlap size
print(i1.overlap_size(i2)) # 5 (overlaps from 5 to 10)
# Test containment
print(i1.contains_point(7)) # True
print(i1.contains_point(15)) # False
print(i2.contains_interval(Interval(6, 9))) # Truefrom intervaltree import Interval
intervals = [
Interval(10, 20, "third"),
Interval(0, 10, "first"),
Interval(5, 15, "second")
]
# Sort intervals
sorted_intervals = sorted(intervals)
# Result: [Interval(0, 10, 'first'), Interval(5, 15, 'second'), Interval(10, 20, 'third')]
# Positional comparisons
i1 = Interval(0, 5)
i2 = Interval(10, 15)
print(i1.lt(i2)) # True (i1 is strictly before i2)
print(i1.distance_to(i2)) # 5 (gap between intervals)Install with Tessl CLI
npx tessl i tessl/pypi-intervaltree