else on the same line - howto

Diez B. Roggisch deets_noospaam at web.de
Wed Oct 15 16:17:27 CEST 2003


> Since Python lacks conditional expression
> 
> like
> 
> k+= (dy >= 0 ? 1 : -1)

You can do it - however, it has some implications:

k += [1,-1][dy < 0]

or

k += [-1,1][dy >= 0]

However, keep in mind that this expression is strictly evaluated. That means
that both parts of the list are evaluated _before_ one is selected using
the boolean index op. That can cause trouble:

k += [expensiveOp1(arg1), expensiveOp2(arg2)][dy >= 0]

will always evaluate both expensiveOps

You can overcome that by lazy evaluation using a lambda:

k += [lambda: expensiveOp1(arg1), lambda: expensiveOp2(arg2)][dy >= 0]()

But this is faar from beeing readable, so in the end I have to agree to the
other posters: Don't do it!

Regards,

Diez




More information about the Python-list mailing list