python-benedict/benedict/core/traverse.py

30 lines
756 B
Python
Raw Normal View History

from benedict.utils import type_util
def _traverse_collection(d, callback):
if type_util.is_dict(d):
_traverse_dict(d, callback)
elif type_util.is_list_or_tuple(d):
_traverse_list(d, callback)
def _traverse_dict(d, callback):
keys = list(d.keys())
for key in keys:
value = d.get(key, None)
callback(d, key, value)
_traverse_collection(value, callback)
2022-03-24 12:26:18 +00:00
def _traverse_list(ls, callback):
items = list(enumerate(ls))
2020-02-05 08:48:50 +00:00
for index, value in items:
2022-03-24 12:26:18 +00:00
callback(ls, index, value)
_traverse_collection(value, callback)
def traverse(d, callback):
if not callable(callback):
2022-02-13 10:35:43 +00:00
raise ValueError("callback argument must be a callable.")
_traverse_collection(d, callback)