Created
November 9, 2017 18:47
-
-
Save kotfic/bb0452285b63737db20a1bc8cb166e55 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _walk_obj(obj, func, leaf_condition=None): | |
"""Walk through a nested object applying func to each leaf element. | |
This function recursively builds a nested structure from a simple | |
object (e.g. dict, list, tuple) by applying func to each element | |
leaf element. By default a leaf node is considered to be any | |
object that is not a dict, list or tuple unless leaf_condition is | |
defined. leaf_condition should be a callable function that | |
returns True or False when passed the object. This allows | |
_walk_obj to consider simple objects that meet certain conditions | |
to be leaf nodes. | |
For example, a dictionary would normally be recursively | |
processed, applying _walk_obj to each value. But, if it contained | |
a certain key, and leaf_condition was a function that checked for | |
that key, then that dictionary would not be recursively processed | |
but passed directly to func. | |
""" | |
if hasattr(leaf_condition, '__call__'): | |
if leaf_condition(obj): | |
return func(obj) | |
if isinstance(obj, dict): | |
return {k: _walk_obj(v, func, leaf_condition=leaf_condition) | |
for k, v in obj.iteritems()} | |
elif isinstance(obj, list): | |
return [_walk_obj(v, func, leaf_condition=leaf_condition) for v in obj] | |
elif isinstance(obj, tuple): | |
return tuple(_walk_obj(list(obj), func, leaf_condition=leaf_condition)) | |
else: | |
return func(obj) |
Author
kotfic
commented
Nov 9, 2017
"""Walk through a nested object applying func to each leaf element.
This function returns a recursively built structure from a nested
tree of simple container types (e.g. dict, list, tuple) by
applying func to each leaf node in the tree. By default a leaf
node is considered to be any object that is not a dict, list or
tuple. leaf_condition is a callable that can be used to test if certain lists,
tuples or dicts should be considered leaf nodes. leaf_condition will be called with a sub-tree, and should return True if that sub-tree is a leaf node, or False if _walk_obj should continue to descend through the sub-tree.
"""
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment