Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 302
emKaroly Avatar asked Nov 03 '25 03:11

emKaroly


1 Answers

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.

like image 178
Dimitris Fasarakis Hilliard Avatar answered Nov 05 '25 19:11

Dimitris Fasarakis Hilliard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!