1-line idiom to replace if blocks

Andrew Koenig ark at research.att.com
Tue Jan 21 10:22:46 EST 2003


>> I hate code that takes up too many lines and
>> have come up with the ff. idiom to replace
>> many 4 line if statements:

>> result=[value-if-false,value-if-true][condition]

>> This idea could also be applied as a compact
>> switch block replacement in certain cases.

Erik> This works if you don't need to worry about short-circuiting
Erik> issues (i.e., you don't even want the true/false cases
Erik> _evaluated_ unless you're the selected), and you're sure that
Erik> the condition expression will evaluate to either 0 or 1.

Erik> In 2.2.x and greater, you can use [x, y][bool(p)] to get this;
Erik> prior to 2.2 you could use [x, y][operator.truth(p)].
Erik> Obviously, a tuple instead of a list will work just as well: (x,
Erik> y)[bool(p)].

And, of course, if you really want short-circuiting, you can write this:

    result=[lambda:value-if-false, lambda:value-if-true][condition]()

That is, if you don't mind people giving you funny looks on the street.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark




More information about the Python-list mailing list