Skip to content

Instantly share code, notes, and snippets.

@Granitosaurus
Created September 18, 2020 10:14
Show Gist options
  • Save Granitosaurus/c13574bc9eba923cc866d2c92f37ac2b to your computer and use it in GitHub Desktop.
Save Granitosaurus/c13574bc9eba923cc866d2c92f37ac2b to your computer and use it in GitHub Desktop.
python object hook
def object_hook(dict_, func: Callable, types: Union[Tuple[Type], Type] = dict):
"""
object hook for python dictionary - applies function to every object of type recursively
note: dictionary keys are not considered to be objects and will be type matched,
for processing dictionary keys you should process whole dict type.
example:
>>> object_hook({'foo': 'bar'}, str.upper, str)
{'foo': 'BAR'}
>>> object_hook({'foo': {'nested': 10}}, lambda v: v+1, int)
{'foo': {'nested': 11}}
"""
new = deepcopy(dict_)
if isinstance(dict_, types): # hook self as well
new = func(new)
if not isinstance(new, collections.MutableMapping):
return new
for key in new:
# recursive object_hook for dicts
if isinstance(new[key], collections.MutableMapping):
new[key] = object_hook(new[key], func, types)
# for lists either apply function if type matched or recursive object_hook if dict
elif isinstance(new[key], (list, tuple)):
new[key] = type(new[key])(
object_hook(v, func, types) if
isinstance(v, collections.MutableMapping) else func(v)
if isinstance(v, types) else v
for v in new[key]
)
if isinstance(new[key], types):
new[key] = func(new[key])
return new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment