Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - applying tupple to a function in functional toolz.pipe

I want to use a function which accepts some arguments in a toolz.pipe, but data input is a tuple. I know how to solve it, but I think there must be some solution in builtin python libraries or in toolz, I just wasnt able to find it.

Example:

def my_func(a, b):
    return a + b

result = pipe(
    (10, 20),
    my_func,
    ...,
)

For those unfamiliar with toolz, pipe is something like:

def pipe(val, *functions):
    data = val
    for fn in functions:
        data = fn(data)
    return data

What I tried:

I know how to solve it, for example this way:

result = pipe(
    (10, 20),
    lambda x: my_func(*x),
    ...,
)

But I find this ugly and I'd like to be able to use some sort of apply function which encapsulates that lambda. I defined mine apply_ like this:

from toolz import pipe

def my_func(a, b):
    return a + b

def apply_(func):
    return lambda x: func(*x)

result = pipe(
    (10, 20),
    apply_(my_func),
)
print(result)

But this seems like something so basic, I'm almost convinced it must exist in builtin python libraries or in toolz package..

Question:

Is there some form of apply wrapper like I described above (apply_), which I have overlooked?

like image 416
Jan Spurny Avatar asked Aug 26 '26 12:08

Jan Spurny


1 Answers

For example:

import toolz
import itertools

def my_func(a, b):
    return a + b


list(toolz.pipe(
    [(10, 20), (30, 40)],
    toolz.curry(itertools.starmap)(my_func)
))

The output:

[30, 70]

Edit I was wrong with my intial solution, but I think itertools's starmap is the way to go.

like image 58
Drey Avatar answered Aug 29 '26 01:08

Drey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!