traversal.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import collections.abc
  2. import contextlib
  3. import inspect
  4. import itertools
  5. import re
  6. from ._utils import (
  7. IDENTITY,
  8. NO_DEFAULT,
  9. LazyList,
  10. int_or_none,
  11. is_iterable_like,
  12. try_call,
  13. variadic,
  14. )
  15. def traverse_obj(
  16. obj, *paths, default=NO_DEFAULT, expected_type=None, get_all=True,
  17. casesense=True, is_user_input=False, traverse_string=False):
  18. """
  19. Safely traverse nested `dict`s and `Iterable`s
  20. >>> obj = [{}, {"key": "value"}]
  21. >>> traverse_obj(obj, (1, "key"))
  22. "value"
  23. Each of the provided `paths` is tested and the first producing a valid result will be returned.
  24. The next path will also be tested if the path branched but no results could be found.
  25. Supported values for traversal are `Mapping`, `Iterable` and `re.Match`.
  26. Unhelpful values (`{}`, `None`) are treated as the absence of a value and discarded.
  27. The paths will be wrapped in `variadic`, so that `'key'` is conveniently the same as `('key', )`.
  28. The keys in the path can be one of:
  29. - `None`: Return the current object.
  30. - `set`: Requires the only item in the set to be a type or function,
  31. like `{type}`/`{func}`. If a `type`, returns only values
  32. of this type. If a function, returns `func(obj)`.
  33. - `str`/`int`: Return `obj[key]`. For `re.Match`, return `obj.group(key)`.
  34. - `slice`: Branch out and return all values in `obj[key]`.
  35. - `Ellipsis`: Branch out and return a list of all values.
  36. - `tuple`/`list`: Branch out and return a list of all matching values.
  37. Read as: `[traverse_obj(obj, branch) for branch in branches]`.
  38. - `function`: Branch out and return values filtered by the function.
  39. Read as: `[value for key, value in obj if function(key, value)]`.
  40. For `Iterable`s, `key` is the index of the value.
  41. For `re.Match`es, `key` is the group number (0 = full match)
  42. as well as additionally any group names, if given.
  43. - `dict` Transform the current object and return a matching dict.
  44. Read as: `{key: traverse_obj(obj, path) for key, path in dct.items()}`.
  45. `tuple`, `list`, and `dict` all support nested paths and branches.
  46. @params paths Paths which to traverse by.
  47. @param default Value to return if the paths do not match.
  48. If the last key in the path is a `dict`, it will apply to each value inside
  49. the dict instead, depth first. Try to avoid if using nested `dict` keys.
  50. @param expected_type If a `type`, only accept final values of this type.
  51. If any other callable, try to call the function on each result.
  52. If the last key in the path is a `dict`, it will apply to each value inside
  53. the dict instead, recursively. This does respect branching paths.
  54. @param get_all If `False`, return the first matching result, otherwise all matching ones.
  55. @param casesense If `False`, consider string dictionary keys as case insensitive.
  56. The following are only meant to be used by YoutubeDL.prepare_outtmpl and are not part of the API
  57. @param is_user_input Whether the keys are generated from user input.
  58. If `True` strings get converted to `int`/`slice` if needed.
  59. @param traverse_string Whether to traverse into objects as strings.
  60. If `True`, any non-compatible object will first be
  61. converted into a string and then traversed into.
  62. The return value of that path will be a string instead,
  63. not respecting any further branching.
  64. @returns The result of the object traversal.
  65. If successful, `get_all=True`, and the path branches at least once,
  66. then a list of results is returned instead.
  67. If no `default` is given and the last path branches, a `list` of results
  68. is always returned. If a path ends on a `dict` that result will always be a `dict`.
  69. """
  70. casefold = lambda k: k.casefold() if isinstance(k, str) else k
  71. if isinstance(expected_type, type):
  72. type_test = lambda val: val if isinstance(val, expected_type) else None
  73. else:
  74. type_test = lambda val: try_call(expected_type or IDENTITY, args=(val,))
  75. def apply_key(key, obj, is_last):
  76. branching = False
  77. result = None
  78. if obj is None and traverse_string:
  79. if key is ... or callable(key) or isinstance(key, slice):
  80. branching = True
  81. result = ()
  82. elif key is None:
  83. result = obj
  84. elif isinstance(key, set):
  85. assert len(key) == 1, 'Set should only be used to wrap a single item'
  86. item = next(iter(key))
  87. if isinstance(item, type):
  88. if isinstance(obj, item):
  89. result = obj
  90. else:
  91. result = try_call(item, args=(obj,))
  92. elif isinstance(key, (list, tuple)):
  93. branching = True
  94. result = itertools.chain.from_iterable(
  95. apply_path(obj, branch, is_last)[0] for branch in key)
  96. elif key is ...:
  97. branching = True
  98. if isinstance(obj, collections.abc.Mapping):
  99. result = obj.values()
  100. elif is_iterable_like(obj):
  101. result = obj
  102. elif isinstance(obj, re.Match):
  103. result = obj.groups()
  104. elif traverse_string:
  105. branching = False
  106. result = str(obj)
  107. else:
  108. result = ()
  109. elif callable(key):
  110. branching = True
  111. if isinstance(obj, collections.abc.Mapping):
  112. iter_obj = obj.items()
  113. elif is_iterable_like(obj):
  114. iter_obj = enumerate(obj)
  115. elif isinstance(obj, re.Match):
  116. iter_obj = itertools.chain(
  117. enumerate((obj.group(), *obj.groups())),
  118. obj.groupdict().items())
  119. elif traverse_string:
  120. branching = False
  121. iter_obj = enumerate(str(obj))
  122. else:
  123. iter_obj = ()
  124. result = (v for k, v in iter_obj if try_call(key, args=(k, v)))
  125. if not branching: # string traversal
  126. result = ''.join(result)
  127. elif isinstance(key, dict):
  128. iter_obj = ((k, _traverse_obj(obj, v, False, is_last)) for k, v in key.items())
  129. result = {
  130. k: v if v is not None else default for k, v in iter_obj
  131. if v is not None or default is not NO_DEFAULT
  132. } or None
  133. elif isinstance(obj, collections.abc.Mapping):
  134. result = (try_call(obj.get, args=(key,)) if casesense or try_call(obj.__contains__, args=(key,)) else
  135. next((v for k, v in obj.items() if casefold(k) == key), None))
  136. elif isinstance(obj, re.Match):
  137. if isinstance(key, int) or casesense:
  138. with contextlib.suppress(IndexError):
  139. result = obj.group(key)
  140. elif isinstance(key, str):
  141. result = next((v for k, v in obj.groupdict().items() if casefold(k) == key), None)
  142. elif isinstance(key, (int, slice)):
  143. if is_iterable_like(obj, collections.abc.Sequence):
  144. branching = isinstance(key, slice)
  145. with contextlib.suppress(IndexError):
  146. result = obj[key]
  147. elif traverse_string:
  148. with contextlib.suppress(IndexError):
  149. result = str(obj)[key]
  150. return branching, result if branching else (result,)
  151. def lazy_last(iterable):
  152. iterator = iter(iterable)
  153. prev = next(iterator, NO_DEFAULT)
  154. if prev is NO_DEFAULT:
  155. return
  156. for item in iterator:
  157. yield False, prev
  158. prev = item
  159. yield True, prev
  160. def apply_path(start_obj, path, test_type):
  161. objs = (start_obj,)
  162. has_branched = False
  163. key = None
  164. for last, key in lazy_last(variadic(path, (str, bytes, dict, set))):
  165. if is_user_input and isinstance(key, str):
  166. if key == ':':
  167. key = ...
  168. elif ':' in key:
  169. key = slice(*map(int_or_none, key.split(':')))
  170. elif int_or_none(key) is not None:
  171. key = int(key)
  172. if not casesense and isinstance(key, str):
  173. key = key.casefold()
  174. if __debug__ and callable(key):
  175. # Verify function signature
  176. inspect.signature(key).bind(None, None)
  177. new_objs = []
  178. for obj in objs:
  179. branching, results = apply_key(key, obj, last)
  180. has_branched |= branching
  181. new_objs.append(results)
  182. objs = itertools.chain.from_iterable(new_objs)
  183. if test_type and not isinstance(key, (dict, list, tuple)):
  184. objs = map(type_test, objs)
  185. return objs, has_branched, isinstance(key, dict)
  186. def _traverse_obj(obj, path, allow_empty, test_type):
  187. results, has_branched, is_dict = apply_path(obj, path, test_type)
  188. results = LazyList(item for item in results if item not in (None, {}))
  189. if get_all and has_branched:
  190. if results:
  191. return results.exhaust()
  192. if allow_empty:
  193. return [] if default is NO_DEFAULT else default
  194. return None
  195. return results[0] if results else {} if allow_empty and is_dict else None
  196. for index, path in enumerate(paths, 1):
  197. result = _traverse_obj(obj, path, index == len(paths), True)
  198. if result is not None:
  199. return result
  200. return None if default is NO_DEFAULT else default
  201. def get_first(obj, *paths, **kwargs):
  202. return traverse_obj(obj, *((..., *variadic(keys)) for keys in paths), **kwargs, get_all=False)
  203. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  204. for val in map(d.get, variadic(key_or_keys)):
  205. if val is not None and (val or not skip_false_values):
  206. return val
  207. return default