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.

1

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

But we cannot reuse the partial function object, for different functions. :)
@thefourtheye, it is seldom that you will need such a flexible wrapper in real-life projects.
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.

Comments

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")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.