1-line idiom to replace if blocks
Robin Munn
rmunn at pobox.com
Fri Jan 24 12:10:04 EST 2003
Y2KYZFR1 <jarrodhroberson at yahoo.com> wrote:
> "Jonathan P." <jbperez808 at yahoo.com> wrote in message news:<3e2cf624 at post.usenet.com>...
>> **** Post for FREE via your newsreader at post.usenet.com ****
>>
>> 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.
>>
>
> God I feel sorry for anyone that has to come behind you and work on
> any code you ever write. If you are this lazy not to write out a
> simple if statement where other people can come behind you and
> understand it.
>
> The entire idea behind Python even more so than other languages is
> maintance and readablity and you whack jobs just insist on making it
> convoluted and obfuscated!
>
> It does not show how clever you are, just how lazy and inconsiderate
> you are. I have fired people for less than this personally!
Let's keep the heat down, shall we? Here, have an iced tea. :-)
Actually, there are occasional times when being able to express an
if-then-else statement in a single expression is very useful
(*cough*lambda*cough*). Most of the time, writing out the complete
if-then-else is better, yes. But there may be times when using a 1-line
idion may result in cleaner-looking code. Let's say you're registering a
bunch of callback functions:
# The idiom [false_val,true_val][condition] is equivalent to the C
# idiom (condition ? true_val : false_val)...
register_callback(1, lambda retval: ['Error','OK'][bool(retval)])
register_callback(2, lambda retval: ['Error','OK'][bool(retval)])
register_callback(3, lambda retval: ['Error','OK'][bool(retval)])
register_callback(4, lambda retval: ['Error','OK'][bool(retval)])
register_callback(5, lambda retval: ['Error','OK'][bool(retval)])
register_callback(6, lambda retval: ['Error','OK'][bool(retval)])
And so on. This example is somewhat contrived, but not extremely so,
unfortunately. I expect I will encounter occasional times when I'll need
to use a a?b:c-like idiom and nothing else will do...
--
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838
More information about the Python-list
mailing list