Reputation: 818
I would like to do something like the following:
def getFunction(params):
f= lambda x:
do stuff with params and x
return f
I get invalid syntax on this. What is the Pythonic/correct way to do it?
This way I can call f(x)
without having to call f(x,params)
which is a little more messy IMO.
Upvotes: 7
Views: 3449
Reputation: 14126
You can't have a multiline lambda expression in Python, but you can return a lambda or a full function:
def get_function1(x):
f = lambda y: x + y
return f
def get_function2(x):
def f(y):
return x + y
return f
Upvotes: 2
Reputation: 59238
It looks like what you're actually trying to do is partial function application, for which functools
provides a solution. For example, if you have a function multiply()
:
def multiply(a, b):
return a * b
... then you can create a double()
function1 with one of the arguments pre-filled like this:
from functools import partial
double = partial(multiply, 2)
... which works as expected:
>>> double(7)
14
1 Technically a partial
object, not a function, but it behaves in the same way.
Upvotes: 6
Reputation: 122150
A lambda
expression is a very limited way of creating a function, you can't have multiple lines/expressions (per the tutorial, "They are syntactically restricted to a single expression"). However, you can nest standard function def
initions:
def getFunction(params):
def to_return(x):
# do stuff with params and x
return to_return
Functions are first-class objects in Python, so once defined you can pass to_return
around exactly as you can with a function created using lambda
, and either way they get access to the "closure" variables (see e.g. Why aren't python nested functions called closures?).
Upvotes: 10