Skip to content

Commit dc92fb2

Browse files
committed
fix(utilities): Enhance ranges_to_string for improved clarity
Updates the `ranges_to_string` function to handle single-value ranges and improve string representation. Refines the formatting logic to include isolated values when the lower and upper bounds of a range are identical. Fixes #20475
1 parent f23eb53 commit dc92fb2

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

netbox/utilities/data.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,16 +137,24 @@ def check_ranges_overlap(ranges):
137137

138138
def ranges_to_string(ranges):
139139
"""
140-
Generate a human-friendly string from a set of ranges. Intended for use with ArrayField. For example:
141-
[[1, 100)], [200, 300)] => "1-99,200-299"
140+
Converts a list of ranges into a string representation.
141+
142+
This function takes a list of range objects and produces a string
143+
representation of those ranges. Each range is represented as a
144+
hyphen-separated pair of lower and upper bounds, with inclusive or
145+
exclusive bounds adjusted accordingly. If the lower and upper bounds
146+
of a range are the same, only the single value is added to the string.
147+
148+
Example:
149+
[NumericRange(1, 5), NumericRange(8, 9), NumericRange(10, 12)] => "1-5,8,10-12"
142150
"""
143151
if not ranges:
144152
return ''
145153
output = []
146154
for r in ranges:
147155
lower = r.lower if r.lower_inc else r.lower + 1
148156
upper = r.upper if r.upper_inc else r.upper - 1
149-
output.append(f'{lower}-{upper}')
157+
output.append(f"{lower}-{upper}" if lower != upper else str(lower))
150158
return ','.join(output)
151159

152160

0 commit comments

Comments
 (0)