Composition of multiple functions onto one, each at a certain keyword

185 Views Asked by At

I have three functions:

def addition(a: int, b: int):
  return a + b

def increment(x: float) -> int:
  return int(x) + 1

def decrement(y: int) -> int:
  return x - 1

I would like to compose increment and decrement on top of addition to get a function which has the signature of new structure. Note that I don't want yet to run the resulting function (lazy composition).

How would I do such a thing when things like toolz.compose expect one input/output of the composed functions, and functools.partial or toolz.curry cannot get a function as a parameter (they treat it as if it were a value).

Essentially I'm looking for the higher order version of partial/curry.

EDIT: I can't use a lambda because I want the new function to have the signature of int and float, and I want to be able to get this signature from the resulting function using inspect.signature.

So given functions a, b and c, and certain keywords k1 and k2, I'd like to connect a, b on top of c, on keywords k1 and k2, and get a function with signature of the params of a concatenated with the params of b.

If we stick to the example above, I want something like:

new_func = pipeline(addition, via("a"), increment, via("b") decrement)

where via composes a function onto an unbound keyword of the pipeline so far.

The result, new_func, would be a function that expects two variables, x: float and y: int and returns an int.

1

There are 1 best solutions below

1
ma3oun On

How about using a lambda function ?

ask_and_add = lambda : addition(get_input(),get_input())

You can then call it whenever you need it as such:

ask_and_add()

You'll get prompted for two consecutive inputs and you'll get the sum.