I have a function which takes two numpy arrays, x
and y
, as arguments. I want to be able to pass in only one argument, y
. How can I return a function that accepts x
, with y
embedded in original function?
For example:
def z(x: [x1, x2, x3], y: [y1, y2, y3]):
return x1 * y1 x2 * y2 x3 * y3
I want z(y=[2, 3, 4])
to return x1 * 2 x2 * 3 x3 * 4
as a new function.
CodePudding user response:
Use functools.partial
:
>>> from functools import partial
>>> z_with_y = partial(z, y=[2,3,4])
>>> z_with_y([5,6,7])
56
>>> z([5,6,7], [2,3,4])
56
CodePudding user response:
Given z = np.dot
, as in your example, or any other 2-arg function, you can make a partial fucuntion
def z1(y):
return lambda x: z(x, y)
Without using lambda
:
def z1(y):
def inner(x):
return z(x, y)
return inner