[Python-list] if the else short form
Brendan Simon (eTRIX)
brendan.simon at etrix.com.au
Wed Sep 29 08:23:31 EDT 2010
On 29/09/10 9:20 PM, python-list-request at python.org wrote:
> Subject:
> if the else short form
> From:
> Tracubik <affdfsdfdsfsd at b.com>
> Date:
> 29 Sep 2010 10:42:37 GMT
>
> To:
> python-list at python.org
>
>
> 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?
>
As others have pointed out, a tuple with two items is created and then
indexed by the integer conversion of conditional. It is "creative"
coding but I wouldn't recommend using it either.
For this particular case you may achieve the same thing with:
button = gtk.Button(str(fill==True))
or possibly just:
button = gtk.Button(fill==True)
It's a little better but still not great.
A verbose form of something more generic may be:
if fill:
label = 'True'
else:
label = 'False'
button = gtk.Button(label)
or possibly:
label = 'True' if fill else 'False'
button = gtk.Button(label)
or using a dict for label lookup:
label = { True : 'True', False : 'False' }
button = gtk.Button(label[fill])
Cheers, Brendan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100929/e975aa24/attachment.html>
More information about the Python-list
mailing list