From dc8f51e2f80c2574579b0640372cf05b2c747fb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Pi=C3=A9dallu?= Date: Thu, 14 Dec 2023 17:21:47 +0100 Subject: [PATCH] Add a new utils.algorithms file for code helpers. The first helper, recursive_apply, goes through recursive dict/lists to apply a function on non-recursable types --- src/utils/algorithms.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/utils/algorithms.py diff --git a/src/utils/algorithms.py b/src/utils/algorithms.py new file mode 100644 index 000000000..02e6205ee --- /dev/null +++ b/src/utils/algorithms.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 + +from typing import Any, Callable + + +def recursive_apply(function: Callable, data: Any) -> Any: + if isinstance(data, dict): # FIXME: hashable? + return {key: recursive_apply(value, function) for key, value in data.items()} + + if isinstance(data, list): # FIXME: iterable? + return [recursive_apply(value, function) for value in data] + + return function(data)