Reverse currying in python

Suppose I have a function like this:

from toolz.curried import *

@curry
def foo(x, y):
    print(x, y)

Then I can call:

foo(1,2)
foo(1)(2)

Both are returning as expected.

However, I would like to do something like this:

@curry.inverse # hypothetical
def bar(*args, last):
    print(*args, last)

bar(1,2,3)(last)

The idea is that I would like to pre-configure the function and then put it in such a channel:

pipe(data,
    f1, # another function
    bar(1,2,3) # unknown number of arguments
)

It bar(1,2,3)(data)will then be called as part of the channel. However, I do not know how to do this. Any ideas? Thank you very much!

Edit:

A more graphic example was requested. So here:

import pandas as pd
from toolz.curried import *

df = pd.DataFrame(data)

def filter_columns(*args, df):
    return df[[*args]]

pipe(df,
    transformation_1,
    transformation_2,
    filter_columns("date", "temperature")
)

As you can see, a DataFrame is passed through functions, and filter_columnsone of them is passed . However, the function is preconfigured and returns a function that accepts only a DataFrame similar to a decorator. The same behavior can be achieved with this:

def filter_columns(*args):
    def f(df):
        return df[[*args]]
    return f

, , filter_columns()(df), .

+6
1

toolz, , , - .

def filter_columns(*args):
    def f(df):
        return df[*args]
    return f

(, , df[*args] )

filter_columns()(data), args , ,

def filter_columns(*argv):
    df, columns = argv[-1], argv[:-1]
    return df[columns]

filter_columns(df), filter_columns("date", "temperature", df) ..

functools.partial, , , ,

from functools import partial
from toolz.curried import pipe # always be explicit with your import, the last thing you want is import something you don't want to, that overwrite something else you use

pipe(df,
    transformation_1,
    transformation_2,
    partial(filter_columns, "date", "temperature")
)
+2

Source: https://habr.com/ru/post/1014651/


All Articles