I have implemented a through
function for myself in a project.
Since I am still quite new in python and want to learn it correctly, I would be happy about any feedback including style, variable naming...
A first question is how to name the function. Because of Mathematica's documentation I called it through
. Is there a more intuitive name?
def through(list_of_functions, value, recurse_level=np.infty):
"""Calls each function in a list
This function is passing the value as argument to each function
in a list.
For a one dimensional list consisting of
only functions it is equivalent to::
[f(value) for f in list]
If an element is not callable and not iterable, it is not called.
An iterable is either directly appended or will be recursed through
depending on recurse_level.
Args:
list_of_functions (list):
value (any type):
recurse_level (int):
Returns:
list:
"""
new_list = []
for possible_function in list_of_functions:
try:
new_list.append(possible_function(value))
except TypeError: # item not callable; could be iterable
# If it is iterable and recurse_level is not negative
# recurse through elements
if recurse_level >= 0:
try:
new_list.append(through(possible_function,
value,
recurse_level))
recurse_level = recurse_level - 1
except TypeError: # not an iterable; append without calling
new_list.append(possible_function)
else:
new_list.append(possible_function)
return new_list
An example:
In: test = [[1, 2], [3, (lambda x : x ** 2)], (lambda x : x ** 3)]
In: through(test, 4, recurse_level=1)
Out: [[1, 2], [3, 16], 64]
In: through(test, 4, recurse_level=0)
Out: [[1, 2], [3, <function __main__.<lambda>>], 64]