0

I have this function f(x, a, b):

def f(x, a, b):
    return a*x + b

and I have to pass this function to another one with 'a' and 'b' pre-set, e.g.:

def print2(f):
    x = np.linspace(0,1,10)
    print(f(x))

print2(f( , 1, 1))

I know that there are other ways to solve this particular problem, however this is just an example, not the real problem, and I'd like to know if there's anyway to do something like this "print2(f( , 1, 1))". In other words, is there anyway to do this without having to pass the arguments all the way through? Like,

def print3(f, a, b):
    x = np.linspace(0, 1, 10)
    print(f(x, a, b))
print3(f, a, b)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
R. Thomes
  • 45
  • 5

3 Answers3

3

You can use functools.partial exactly for that!

def print2(f):
    x = np.linspace(0,1,10)
    print(f(x))
f2 = functools.partial(f, a=1, b=2)
print2(f2)

For the many possible advantages gained by using partial, see this.

In short:

and many more...

Bharel
  • 23,672
  • 5
  • 40
  • 80
1

You can just wrap it in another function:

g = lambda x: f(x, 1, 1)

print2(g)

Make the arguments of the outer function whatever data still needs to be supplied, and pass that data through.


I'm being told that this approach isn't ideal in Python. @Bharel's answer is likely more appropriate.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • Hadn't downvoted but while you can use a lambda, it's not a very good idea compared to partial functions. – Bharel Apr 04 '19 at 17:26
  • Nope, for quite a few reasons. From introspection to compatibility. – Bharel Apr 04 '19 at 17:31
  • @Bharel Well, my bad. This is just how I'd do it in other languages. I was unaware of the problems in Python. – Carcigenicate Apr 04 '19 at 17:34
  • 1
    Oh sure, much like I don't know all the small nuances in Java you might not know about this :-) As for more reasons, see [this](https://stackoverflow.com/questions/3252228/python-why-is-functools-partial-necessary) – Bharel Apr 04 '19 at 17:36
0

Both lambda and partial are fancy ways of creating a new function. You can also just write it yourself:

def f2(x):
    return f(x, 1, 1)

What makes lambda and partial special is that they are expressions and can be passed as arguments to higher-order functions directly.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65