emKaroly
emKaroly

Reputation: 796

How to modify a variable inside a lambda function?

I am trying to do something like this:

def myFunc(y):
    aVariable = "a"
    bVariable = "b"
    y(aVariable,bVariable)

def main():
    myFunc(lambda a,b: a+=b)

and expecting the output to be "ab".

Instead I get the following error:

File "<stdin>", line 7
  myFunc(lambda x, y: x += y)
                        ^
SyntaxError: invalid syntax

Upvotes: 4

Views: 4140

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

Only expressions are allowed in the body of a lambda function; a += b is an augmented assignment statement, when compiled, this will lead to a SyntaxError as the grammar doesn't allow it.

You can either change it to simply return the addition:

lambda a,b: a+b

and then proceed to set the result of calling it to a appropriately:

a = y(aVariable,bVariable)

You could of course resort to using the function that is used for that operation. Though you could directly do lambda a, b: a.__iadd__(b), this is clunky and using dunders like this isn't the best practice. Instead, you should use the appropriate operation from the operator module.

The iadd function from operator allows you to bypass this "restriction" if you truly need to. Function calls are expressions, as such, it is allowed to use them in the body of the lambda function. A simple import is needed:

from operator import iadd

and then, redefine the lambda passed to myFunc to use iadd:

myFunc(lambda a,b: iadd(a, b))

Adding these all together while also adding appropriate returns in myFunc and main:

from operator import iadd

def myFunc(y):
    aVariable = "a"
    bVariable = "b"
    return y(aVariable,bVariable)

def main():
    return myFunc(lambda a,b: iadd(a, b))

results in ab when main is called.

Upvotes: 11

Related Questions