Search code examples
pythonfunctionargumentscallpartial

Assigning a function with another function as parameter to a variable in Python


Let's say I have the following 2 functions:

def add(*numbers, squared=False):
   return (sum(numbers) ** 2) if squared else sum(numbers)
def multiply(*numbers, half=False):
    mult = 1
    for i in numbers:
        mult *= i
    return (mult / 2) if half else mult

What I want to do is assign a variable (multiply_add) so that I can use it as a function and pass parameters to it but in reality, it's just the multiply function that takes the return of the add function as the first parameter but I'm the one who actually gives the numbers for the add function as well.

So basically something like this:

multiply_add = multiply(add(NUMBERS))

# And I can call it like so:
multiply_add((5, 3, 2), 7, half=True)

# In this case the result would be 35.0 (add = 10, then 10*7 = 70 / 2 = 35)

The above is just an example (and not even a very good one) but I think the idea is clear. Please don't suggest anything that's only applicable to the given code but not the idea itself.

I tried using the partial function from the functools library but I couldn't figure out how to use it so I can achieve what I want.

I'm aware that I can just write a new function and deal with all that but I'm asking if there's a simpler method like using the partial function or something else I can't think of at the moment.

I'm very sorry for this question, I'm sure there's already an answer to it somewhere but I didn't know what to search for and so couldn't find an answer.


Solution

  • it seems what you are looking for is lambda. Using it you can do

    multiply_add = lambda a, b, half: multiply(add(*a), b, half=half)
    multiply_add((5, 3, 2), 7, half=True)  # will return 35
    

    type hinting lambda can be done by importing Callable from the typing module and using it like this:

    multiply_add: Callable[[tuple[int], int, bool], int | float] = lambda a, b, half: multiply(add(*a), b, half=half)