Home > Blockchain >  Can I pre-specify all but one of the arguments in python function to return a callable in python
Can I pre-specify all but one of the arguments in python function to return a callable in python

Time:08-06

Let's say I define a function in python

def f(x,y):
   return(x y)

Now I want to define a function g( __ )=f( __ ,y), i.e. a function for which I already specified a value y and want it to be a callable which takes only one argument. Is there an elegant way to do this?

CodePudding user response:

You could write a simple lambda function like

g = lambda x: f(x, 100)

CodePudding user response:

functools.partial is what you need: https://docs.python.org/3/library/functools.html

from functools import partial
g = partial(f, y=your_constant_value_for_y)

Calling g(x) is equivalent to calling f(x, your_constant_value_for_y).

CodePudding user response:

In case, you have to pass many arguments:

def f(x, *args):
    return (x, args)


def g(x):
    return f(x, 10, 20, 20)
  • Related