No, question's not duplicate. It isn't about "How to say a=1
in python"?
And isn't trivial. Please read carefully.
Answer is: it's impossible to create such a one-liner, at least without using dirty hacks. See the accepted answer for details.
And if you don't want to read, but came here for easy karma, please pass by and stop minusing me, cause the accepted answer is very useful. :)
Question:
I'm doing some GUI programming and want to create a very short signal handler that would set local variable to a value in response to a signal from GUI.
def function():
output = False #this is local variable; I want to change its value by signal handler
button = PyQt4.QtGui.QPushButton("simple button")
#next line sets output to True
button.pressed.connect(lambda:SOME_FUNCTION_I_AM_LOOKING_FOR(output, True))
#Now output==True
Could you suggest, what to substitute for SOME_FUNCTION_I_AM_LOOKING_FOR
? Obviously, you can't just say button.pressed.connect(output=True)
, cause output=True
isn't a function.
To illustrate what I'm looking for here's an analogue: if you want to set an object's attribute, you can use setattr
function. Here's an analogue of code above, setting attribute instead of local variable:
def function():
...
#create a dummy UserObject class and make an instance of it to store attributes
output_object = type('UserObject', (), {})()
output_object.it_was_pressed = False #flags that button was pressed
#when "pressed" signal of button is emitted, "it_was_pressed" attribute of output_object is set to True
button = PyQt4.QtGui.QPushButton("simple button")
button.pressed.connect(lambda: setattr(output_object, "it_was_pressed", True)
That's not what I want to do. What I want to do is create an analogue of this to set a local variable in response to signal:
UPDATE:
I'm asking for one-liner solution: concise and elegant. Of course, I could do this in 3 lines, but I don't want to.