0

I have a function-object f, which takes 4 numeric inputs and outputs two numbers. Maybe

def  f(a, b, c, d):
    return a+b, c+d

or maybe

def  f(a, b, c, d):
    return a*c, d*c

To be clear, I don't actually know what f is, I just have it as an object.

I would like to create a new function-object, h, such that h(a,b,c,d)=x*c+y where (x,y)=f(a,b,c,d). The trouble is, I have no direct access to c, only to f.

def  make_h(f):
   ???
   return h

assert( make_h(f)(a,b,c,d) == f(a,b,c,d)[0]*c+f(a,b,c,d)[1])

Is it possible to do this in python? I have tried searching and reading some documentation, but have not found an answer (yet?).

EDIT: There is a simple answer (given below) when the signature of f is fixed. Suppose I had to do this to different functions, some with inputs (a, b, c, d), some with inputs (l, m, c), and maybe some with inputs (c, r). Would it still be possible to do what I want?

1 Answer 1

6

This example is strongly related to the concept of a decorator. My solution is the following:

def make_h(f):
   def h(a, b, c, d):
       x, y = f(a,b,c,d)
       return x * c + y
   return h

UPDATE. In case f has any number of arguments, we can use args, and kwargs. While it is a bad practice, if we know that one of kwargs is c, we could use the following code:

def make_h(f):
   def h(*args, **kwargs):
       x, y = f(*args, **kwargs)
       return x * kwargs["c"] + y
   return h
2
  • Thank you. In my question I explicitly stated the signature of f, and this is a great answer for that case. I wonder if it's still possible to do this if, say, the number of inputs to f varies and, more generally, all I know is that f has an input called 'c'. I hope it would not be considered bad behaviour if I'll edit the question to ask for that as well.
    – Max M
    Commented Aug 25, 2021 at 6:01
  • See the answer above. Commented Aug 25, 2021 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.