Short if

Paul Rubin http
Thu Jul 8 21:58:33 CEST 2004


"Paul Sweeney" <reverse.ku.oc.issolok at nothypgnal.delrest.co.uk> writes:
> >   bool = false
> >   string = 'This is ' + (( bool ) ? 'true' : 'false')
> 
> If you are really convinced that this is a good road to go down (think of
> code readability), you could do
> 
>     bool = False   # check capitalisation!
>     string = 'This is ' + ('false','true')[bool]

But that can easily become incorrect when the branches have side effects:

     string = 'This is ' + (false(), true())[bool]

You have to do something like:

    string = 'This is ' + (lambda: false(), lambda: true())[bool]()

> I never liked the C ? operator, always finding code was clearer using the
> full if, and this hack is even worse!

Which is more readable depends on the context.  Sometimes the 'if'
just bloats up your code.



More information about the Python-list mailing list