Babakslt Babakslt - 1 month ago 6
Python Question

how to send func name as arg with inline loop in python

i'm working on a GUI program and i have two

QCheck
widgets and want to connect them both to a single function. every thing is fine with a code like this:

widgets = [widget1,widget2]
for widget in widgets:
self.connect(widget, SIGNAL("clicked()"), self.TheFunction)


i know it might be very lazy but it must be a way for doing this in a single line way! i'm aware that i can use lambada(right?) but is there any way i can make it work like this?

self.connect((x for x in (widget1,widget2)), SIGNAL("clicked()"),self.TheFunction)


both
widget1
and
widget2
are
QObject
s and this is what the
connect
expect to see. but no matter what i try it always tell me that the arguments are not
QObject
!

Answer

You can write simple for loop in one line

for x in (widget1, widget2): self.connect(x, SIGNAL("clicked()"), self.TheFunction)

If you need to use list comprehension then rather

list(self.connect(x, SIGNAL("clicked()"),self.TheFunction) for x in (widget1,widget2))

or

[self.connect(x, SIGNAL("clicked()"),self.TheFunction) for x in (widget1,widget2)]

(thanks Jean-Fran├žois Fabre)

but your first version in 3 lines is more readable.