pythonfunctional-programmingtoolz

How to pass "extra" parameter to compose function


I' am searching for a way to compose function with an option to pass 'extra' parameter.

Example:

from toolz import compose_left

def g(a, b, c) -> int:
    return a + b + c

def f(a, b = 100) -> int:
    return a + b

when i do this:

compose_left(g, f)(1,2,3)

i get this:

106

cool.

but is there a way to define the parameter b and c from the function g in compose?

like this:

compose_left(g(b=2,c=3), f)(1)

now i get this:

TypeError: g() missing 1 required positional argument: 'a'

I am looking for a function or a package that can do this.


Solution

  • You're looking for functools.partial.

    compose_left(functools.partial(g, b=2, c=3), f)(1)  # 106