Join list of function names into a series of nested function calls

Viewed 47

I have a list of functions names functions stored as a string which I want to nest together to create an expression applied to some input string var:

f1,f2,f3

The end result would be this string:

f1(f2(f3({var})))

How could I go about doing that? I have this which gives what I want, wondering if it can be improved?

functions = 'f1,f2,f3'
var = 'hello'
all_functions = functions.split(',')
'('.join(all_functions) + '(' + var + ')'*len(all_functions)

Result

f1(f2(f3(hello)))
4 Answers

Here's a recursive solution:

def nest(*args):
    if len(args) == 1:
        return args[0]
    return f"{args[0]}({nest(*args[1:])})"

Example:

>>> functions = "f1,f2,f3"
>>> var = "hello"
>>> nest(*functions.split(","), var)
'f1(f2(f3(hello)))'

You don't need to split, saving you a line:

functions.replace(',', '(') + '(' + var + ')' * (functions.count(',') + 1)

You can also use string formatting, e.g., to ensure that var is converted to a string properly:

f'{functions.replace(",", "(")}({var}){")" * functions.count(",")}'

A way with functools.reduce:

reduce('{1}({0})'.format, functions.split(',')[::-1], var)

A recursive function with parameter unpacking would do it elegantly:

def call(func,*params): 
    return f"{func}({call(*params)})" if params else func

functions = 'f1,f2,f3'
var = 'hello'

print(call(*functions.split(","),var))

f1(f2(f3(hello)))
Related