Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return function with function

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.

like image 294
user3391229 Avatar asked Feb 04 '15 15:02

user3391229


3 Answers

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 definitions:

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?).

like image 113
jonrsharpe Avatar answered Oct 06 '22 12:10

jonrsharpe


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.

like image 28
Zero Piraeus Avatar answered Oct 06 '22 11:10

Zero Piraeus


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
like image 32
famousgarkin Avatar answered Oct 06 '22 11:10

famousgarkin