Question
How do I compose or chain multiple function in Python
When writing a program, I often want to perform a series of steps on a piece of data (usually a list or string). For example I might want to call a function which returns a string, convert it to a list, map over the list, and then reduce to get a final result.
In programming languages I've used in the past, I would expect to be able to do something like one of the following:
compose(
getSomeString,
list,
map(someMapFunction)
reduce(someReduceFunction)
)()
getSomeString()
.list()
.map(someMapFunction)
.reduce(someReduceFunction)
getSomeFunction
=> list
=> map(someMapFunction)
=> reduce(someReduceFunction)()
However, I can't figure out a clean and compact way to do composition/chaining in Python. The one exception I've found is that a list comprehension works for the case where I want to compose a map and a filter.
What is the Pythonic way of writing composition oriented code without either having tons of nesting that makes my code look like Lisp:
reduce(
someReduceFunction,
map(
someMapFunction,
list(
getSomeString()
)
)
)
Or creating intermediate values for everything:
myString = getSomeString()
stringAsList = list(myString)
mappedString = map(someMapFunction, stringAsList)
reducedString = reduce(someReduceFunction, mappedString)