0

I have a python function that I can pass a function argument in 2 ways as shown below.

Lambda:

res = foo(lambda x: x+2)

Regular function passing:

def func1(x):
  return x + 2

res = foo(func1)

But I want to pass a slightly complex function to foo similar to the lambda function call. I can easily do this with LUA code.

LUA example:

res = foo(function (x) 
            local y = x * 2 
            if(y %2 == 0) then 
               return y 
            else 
               return y + 1
            end
          end)

How do I accomplish this with Python in a clean, programmer friendly way? All examples of lambda I see are for very minimal logic.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
sgowd
  • 946
  • 3
  • 10
  • 27
  • You lambda can reference a longer def defined unction. Lambdas are expressions and there can only have one statement. – ShpielMeister Feb 01 '20 at 20:57
  • 3
    If you need a complex function, then pass a function - lambdas are intended to be one-liners, if it's something longer than that, then it's not an appropriate use for a lambda. – Óscar López Feb 01 '20 at 20:58
  • @ShpielMeister, I prefer to not define the function outside of the foo call. – sgowd Feb 01 '20 at 20:59
  • @ÓscarLópez, is there a way i can write similar to the LUA example i have given? – sgowd Feb 01 '20 at 21:01
  • 3
    Does this answer your question? [No Multiline Lambda in Python: Why not?](https://stackoverflow.com/questions/1233448/no-multiline-lambda-in-python-why-not) – ShpielMeister Feb 01 '20 at 21:02
  • @ShpielMeister Perfect. Thanks. As a python beginner, I wasn't sure what to ask or what to search for, so i ended up writing a new question. – sgowd Feb 01 '20 at 21:04
  • @sgowd Nope, it's a different language, Python simply doesn't work like that. As I said: if it's more than one line, then you're not supposed to use a lambda in Python. – Óscar López Feb 01 '20 at 21:07
  • @ShpielMeister to be pedantic, a lambda cannot contain a statement, only an expression – juanpa.arrivillaga Feb 01 '20 at 21:16
  • Thanks @ÓscarLópez I was expecting python must be having an alternative to one liner lambda. I see now there isn't. – sgowd Feb 01 '20 at 21:21

0 Answers0