data.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import decimal
  2. from itertools import count, groupby
  3. from django.db.backends.postgresql.psycopg_any import NumericRange
  4. __all__ = (
  5. 'array_to_ranges',
  6. 'array_to_string',
  7. 'check_ranges_overlap',
  8. 'deep_compare_dict',
  9. 'deepmerge',
  10. 'drange',
  11. 'flatten_dict',
  12. 'get_config_value_ci',
  13. 'ranges_to_string',
  14. 'ranges_to_string_list',
  15. 'resolve_attr_path',
  16. 'shallow_compare_dict',
  17. 'string_to_ranges',
  18. )
  19. #
  20. # Dictionary utilities
  21. #
  22. def get_config_value_ci(config_dict, key, default=None):
  23. """
  24. Retrieve a value from a dictionary using case-insensitive key matching.
  25. """
  26. if key in config_dict:
  27. return config_dict[key]
  28. key_lower = key.lower()
  29. for config_key, value in config_dict.items():
  30. if config_key.lower() == key_lower:
  31. return value
  32. return default
  33. def deepmerge(original, new):
  34. """
  35. Deep merge two dictionaries (new into original) and return a new dict
  36. """
  37. merged = dict(original)
  38. for key, val in new.items():
  39. if key in original and isinstance(original[key], dict) and val and isinstance(val, dict):
  40. merged[key] = deepmerge(original[key], val)
  41. else:
  42. merged[key] = val
  43. return merged
  44. def flatten_dict(d, prefix='', separator='.'):
  45. """
  46. Flatten nested dictionaries into a single level by joining key names with a separator.
  47. :param d: The dictionary to be flattened
  48. :param prefix: Initial prefix (if any)
  49. :param separator: The character to use when concatenating key names
  50. """
  51. ret = {}
  52. for k, v in d.items():
  53. key = separator.join([prefix, k]) if prefix else k
  54. if type(v) is dict:
  55. ret.update(flatten_dict(v, prefix=key, separator=separator))
  56. else:
  57. ret[key] = v
  58. return ret
  59. def shallow_compare_dict(source_dict, destination_dict, exclude=tuple()):
  60. """
  61. Return a new dictionary of the different keys. The values of `destination_dict` are returned. Only the equality of
  62. the first layer of keys/values is checked. `exclude` is a list or tuple of keys to be ignored.
  63. """
  64. difference = {}
  65. for key, value in destination_dict.items():
  66. if key in exclude:
  67. continue
  68. if source_dict.get(key) != value:
  69. difference[key] = value
  70. return difference
  71. def deep_compare_dict(source_dict, destination_dict, exclude=tuple()):
  72. """
  73. Return a two-tuple of dictionaries (added, removed) representing the differences between source_dict and
  74. destination_dict. For values which are themselves dicts, the comparison is performed recursively such that only
  75. the changed keys within the nested dict are included. `exclude` is a list or tuple of keys to be ignored.
  76. """
  77. added = {}
  78. removed = {}
  79. all_keys = set(source_dict) | set(destination_dict)
  80. for key in all_keys:
  81. if key in exclude:
  82. continue
  83. src_val = source_dict.get(key)
  84. dst_val = destination_dict.get(key)
  85. if src_val == dst_val:
  86. continue
  87. if isinstance(src_val, dict) and isinstance(dst_val, dict):
  88. sub_added, sub_removed = deep_compare_dict(src_val, dst_val)
  89. if sub_added or sub_removed:
  90. added[key] = sub_added
  91. removed[key] = sub_removed
  92. else:
  93. added[key] = dst_val
  94. removed[key] = src_val
  95. return added, removed
  96. #
  97. # Array utilities
  98. #
  99. def array_to_ranges(array):
  100. """
  101. Convert an arbitrary array of integers to a list of consecutive values. Nonconsecutive values are returned as
  102. single-item tuples.
  103. Example:
  104. [0, 1, 2, 10, 14, 15, 16] => [(0, 2), (10,), (14, 16)]
  105. """
  106. group = (
  107. list(x) for _, x in groupby(sorted(array), lambda x, c=count(): next(c) - x)
  108. )
  109. return [
  110. (g[0], g[-1])[:len(g)] for g in group
  111. ]
  112. def array_to_string(array):
  113. """
  114. Generate an efficient, human-friendly string from a set of integers. Intended for use with ArrayField.
  115. Example:
  116. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  117. """
  118. ret = []
  119. ranges = array_to_ranges(array)
  120. for value in ranges:
  121. if len(value) == 1:
  122. ret.append(str(value[0]))
  123. else:
  124. ret.append(f'{value[0]}-{value[1]}')
  125. return ', '.join(ret)
  126. #
  127. # Range utilities
  128. #
  129. def drange(start, end, step=decimal.Decimal(1)):
  130. """
  131. Decimal-compatible implementation of Python's range()
  132. """
  133. start, end, step = decimal.Decimal(start), decimal.Decimal(end), decimal.Decimal(step)
  134. if start < end:
  135. while start < end:
  136. yield start
  137. start += step
  138. else:
  139. while start > end:
  140. yield start
  141. start += step
  142. def check_ranges_overlap(ranges):
  143. """
  144. Check for overlap in an iterable of NumericRanges.
  145. """
  146. ranges.sort(key=lambda x: x.lower)
  147. for i in range(1, len(ranges)):
  148. prev_range = ranges[i - 1]
  149. prev_upper = prev_range.upper if prev_range.upper_inc else prev_range.upper - 1
  150. lower = ranges[i].lower if ranges[i].lower_inc else ranges[i].lower + 1
  151. if prev_upper >= lower:
  152. return True
  153. return False
  154. def ranges_to_string_list(ranges):
  155. """
  156. Convert numeric ranges to a list of display strings.
  157. Each range is rendered as "lower-upper" or "lower" (for singletons).
  158. Bounds are normalized to inclusive values using ``lower_inc``/``upper_inc``.
  159. This underpins ``ranges_to_string()``, which joins the result with commas.
  160. Example:
  161. [NumericRange(1, 6), NumericRange(8, 9), NumericRange(10, 13)] => ["1-5", "8", "10-12"]
  162. """
  163. if not ranges:
  164. return []
  165. output: list[str] = []
  166. for r in ranges:
  167. # Compute inclusive bounds regardless of how the DB range is stored.
  168. lower = r.lower if r.lower_inc else r.lower + 1
  169. upper = r.upper if r.upper_inc else r.upper - 1
  170. output.append(f"{lower}-{upper}" if lower != upper else str(lower))
  171. return output
  172. def ranges_to_string(ranges):
  173. """
  174. Converts a list of ranges into a string representation.
  175. This function takes a list of range objects and produces a string
  176. representation of those ranges. Each range is represented as a
  177. hyphen-separated pair of lower and upper bounds, with inclusive or
  178. exclusive bounds adjusted accordingly. If the lower and upper bounds
  179. of a range are the same, only the single value is added to the string.
  180. Intended for use with ArrayField.
  181. Example:
  182. [NumericRange(1, 5), NumericRange(8, 9), NumericRange(10, 12)] => "1-5,8,10-12"
  183. """
  184. if not ranges:
  185. return ''
  186. return ','.join(ranges_to_string_list(ranges))
  187. def string_to_ranges(value):
  188. """
  189. Converts a string representation of numeric ranges into a list of NumericRange objects.
  190. This function parses a string containing numeric values and ranges separated by commas (e.g.,
  191. "1-5,8,10-12") and converts it into a list of NumericRange objects.
  192. In the case of a single integer, it is treated as a range where the start and end
  193. are equal. The returned ranges are represented as half-open intervals [lower, upper).
  194. Intended for use with ArrayField.
  195. Example:
  196. "1-5,8,10-12" => [NumericRange(1, 6), NumericRange(8, 9), NumericRange(10, 13)]
  197. """
  198. if not value:
  199. return None
  200. value.replace(' ', '') # Remove whitespace
  201. values = []
  202. for data in value.split(','):
  203. dash_range = data.strip().split('-')
  204. if len(dash_range) == 1 and str(dash_range[0]).isdigit():
  205. # Single integer value; expand to a range
  206. lower = dash_range[0]
  207. upper = dash_range[0]
  208. elif len(dash_range) == 2 and str(dash_range[0]).isdigit() and str(dash_range[1]).isdigit():
  209. # The range has two values and both are valid integers
  210. lower = dash_range[0]
  211. upper = dash_range[1]
  212. else:
  213. return None
  214. values.append(NumericRange(int(lower), int(upper) + 1, bounds='[)'))
  215. return values
  216. #
  217. # Attribute resolution
  218. #
  219. def resolve_attr_path(obj, path):
  220. """
  221. Follow a dotted path across attributes and/or dictionary keys and return the final value.
  222. Parameters:
  223. obj: The starting object
  224. path: The dotted path to follow (e.g. "foo.bar.baz")
  225. """
  226. cur = obj
  227. for part in path.split('.'):
  228. if cur is None:
  229. return None
  230. try:
  231. cur = getattr(cur, part) if hasattr(cur, part) else cur.get(part)
  232. except AttributeError:
  233. cur = None
  234. return cur