Basj
Basj

Reputation: 46453

One-line lambda function that sets a value to a variable

Creating callback functions that set a variable obj.x like this:

def f(button, callback):
    pass

def callback1():
    obj.x = 1
def callback2():
    obj.x = 2

class Obj: 
    pass
obj = Obj()
f('abc', callback2)
f('def', callback1)

is redundant, and can be replaced by:

def xsetter(value):
    obj.x = value

f('abc', lambda: xsetter(1))
f('def', lambda: xsetter(2))

Question: is there even simpler, without having to define a setter for x? Is something similar to the following possible?

f('abc', lambda: obj.x = 1)
f('def', lambda: obj.x = 2)

Here it produces an error:

SyntaxError: lambda cannot contain assignment

Upvotes: 1

Views: 992

Answers (1)

chepner
chepner

Reputation: 531075

Assignments to names aren't (cleanly) possible inside a lambda expression. You, however, are assigning to an attribute, which is handled by the setattr function.

f('abc', lambda: setattr(obj, 'x', 1))

You can also use functools.partial to "partially" apply the object's __setattr__ method to the required arguments.

from functools import partial

f('abc', partial(obj.__setattr__, 'x', 1))

Upvotes: 7

Related Questions