6

I am now trying to pass a multi-variable function F(x, y, z) as an argument of another function G(F, x) in Python. As written, the two arguments in function G is the function F and one of F's variables x. In other words, what I am trying to do is instead of passing F as a three-variable function, I'd rather pass it as a single variable function which depends only on x. The values of y and z are already assigned before calling G.

In Matlab, this is done simply by:

G((@x) F(x, y, z));

I am wondering if there is something similar in Python? I have tried to search online but I am not very familiar with the English wording for this particular question so no luck.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
cipolla
  • 61
  • 1
  • Is G supposed to use the output of F, or will it execute F on its own? It sounds like what you're asking for is called 'currying': http://mtomassoli.wordpress.com/2012/03/18/currying-in-python/ – Maurice Reeves Jan 22 '14 at 14:58

4 Answers4

5

It may be also done with functools.partial

In [158]:from functools import partial

In [159]: adder_w = partial(adder, y=5, z=10)

In [160]: adder_w(2)
Out[160]: 17

EDIT:

Sorry, I've forgotten to include function adder copied (I am lazy :) )from the @thefourtheye's answer

def adder(x, y, z):
    return x + y + z
volcano
  • 3,578
  • 21
  • 28
5

lambda is suitable for this situation.

def G(func, x):
    return func(x)

def F(x, y, z):
    return x+y+z

print G(lambda x: F(x, 1, 2), 3)
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
afkfurion
  • 2,767
  • 18
  • 12
3

You can do it with Python closures and function currying technique, like this

def adder(x, y, z):
    return x + y + z

def wrapper_g(y, z):
    def g(f, x, y = y, z = z):
        return f(x, y, z)  # By closure property, `f` accesses `y` and `z`
    return g

g = wrapper_g(5, 10)       # We are creating `g` with default parameters 5 and 10
print g(adder, 20)         # along with the third parameter 20, adder is called. 
print g(adder, 40)         # along with the third parameter 40, adder is called. 
print g(multiplier, 2)     # We can pass any function, which can act on 2 params.
print g(multiplier, 2, y = 3, z = 4) # We can dynamically alter the default param

Output

35
55
100
24

Advantages:

  1. We can dynamically decide which function to be invoked

  2. We even get to alter the default parameters, while calling.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

It can be as simple as this

def F(x,y,z):
  print "x=",x
  print "y=",y
  print "z=",z

def G(func,x):
  func(x,"G's Y", "G's Z")

G(F,"Main's X")
cgeroux
  • 192
  • 4