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.
multiply_add = lambda numbers: multiply(add(numbers)), but this is generally only used in an anonymous context. You don't wantpartialbecause that's for pre-defining some of the arguments to a function, not pre-defining some of the implementation of it.TrueorFalsetoadd, you could just as easily be deciding whether to calladdoradd_squaredinstead. In general, you could accept an arbitrary pre-processing function (defaultlambda x: x) to apply to each of the numbers before summing the results.