4

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
2
  • 1
    Why doesn't myFunc have a return statement? If you expect y to mutate aVariable &/or bVariable that's not going to happen, no matter what y does, because both aVariable & bVariable are strings, and Python strings are immutable. Commented Dec 8, 2016 at 10:03
  • Right you are, i change my question. Commented Dec 8, 2016 at 10:08

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.