Bartlomiej Lewandowski - 1 year ago 65

Python Question

I have a list of items, coming from one object which are of type A, and a library that operates on object of type B.

I would like to convert A to B, and later call B's function in a pythonic way. What I have come up with so far:

`def convert_A_to_B(A):`

return B(A.something, A.something_else)

def doStuff(a_list):

converted_to_b = list(map(convert_A_to_B, a_list)

return list(map(B.function, converted_to_b))

I could create a lambda to combine these functions, but I feel like there should be an easier way. Something like:

`return list(map(combine(convert_A_to_B, B.function)))`

Answer Source

```
from functools import partial, reduce
combine = lambda *xs: partial (reduce, lambda v,x: x(v), xs)
```

^{The function is usable such as combine (A.foo, A.bar) (x) with is equivalent to A.bar(A.foo (x)).}

^{combine will accept a variadic number of functions, and return a new function that accepts a single value. This value will then be passed through every previously mentioned function (in chain) until a final result is yield.}

```
map (combine (convert_A_to_B, B.function), a_list)
```