On 29 Sep, 18:20, Seebs <usenet-nos...@seebs.net> wrote: > On 2010-09-29, Tracubik <affdfsdfds...@b.com> wrote: > > > Hi all, > > I'm studying PyGTK tutorial and i've found this strange form: > > > button = gtk.Button(("False,", "True,")[fill==True]) > > > the label of button is True if fill==True, is False otherwise. > > > i have googled for this form but i haven't found nothing, so can any of > > you pass me any reference/link to this particular if/then/else form? > > Oh, what a nasty idiom. > > Here's the gimmick. > ("False,", "True,") > is a tuple. That means you can index it. For instance: > ("False,", "True,")[0] > is the string "False,". > > So, what is the numeric value of "fill == True"? Apparently, at least > at the time this was written, it was 0 if fill was not equal to True, > and 1 if fill was equal to True. > > Let me say, though, that I'm a C programmer, so I'm coming from a language > where the result of 0-or-1 for test operators is guaranteed, and I still > wouldn't use this in live code. It's insufficiently legible.
I'm surprised you don't like this construct. I hadn't seen it until I read the OP's question just now. However, it's meaning was immediately apparent. I should say where I'm coming from. Contrast the following C and Python: text = fill == true ? "True," : "False,"; (C) text = ("False,", "True,")[fill == true] (Python) I never liked C's ?: construct partly because it doesn't scale well. To accept more than two options it requires the programmer to build a small hierarchy which can be awful to read and may be best expressed as a separate function. I'd rather have a language change a predicate to a small integer and use that to index a set of results - and this is exactly what the OP's tutorial does. I'm not saying you are wrong, merely expressing a different view and explaining why. As another hypothetical example where sgn() returns -1, 0 or +1 position = ("less", "equal", "greater")[sgn(a - b) + 1] Though where the list gets much longer it would be good to be able to label the cases for legibility. cc. comp.lang.misc James -- http://mail.python.org/mailman/listinfo/python-list