3 ms·
I don't think there's anything wrong with the idiom condition and trueaction or falseaction Am I behind the times? On a separate note, the code in the examp
by thomasmallen 18y ago
I don't think there's anything wrong with the idiom
condition and trueaction or falseaction
Am I behind the times? On a separate note, the code in the examples above is very difficult to read...a lambda really shouldn't be doing if/else operations like these in my opinion.
- kaens 18y agoAlong with the points other people have made, trueaction if condition else falseaction is marginally more clear than condition and trueaction or falseaction , at least to people who aren't used to seeing and/or used like that. A lot of people, especially newer programmers, aren't used to seeing and...or used for branching that directly.
- globalrev 18y agoThe formatting got messed up but yes I agree. They were just examples, not the best ones perhaps. I have felt a need for it sometimes though. Very complicated lambdas are perhaps generally better off as normal functions. But I hate creating one-time-use functions if it isn't necessary.
- brianr 18y agoThe problem with that construct is that trueaction itself must evaluate to true, or the expression will evaluate to falseaction, which most likely is not what you want: >>> 0 if 1 else 2 0 >>> 1 and 0 or 2 2 Even crazier things can happen if trueaction has side effects: >>> def trueaction(): ... print 'trueaction called' ... return 0 ... >>> def falseaction(): ... print 'falseaction called' ... return 'hello' ... >>> True and trueaction() or falseaction() trueaction called falseaction called 'hello' >>> trueaction() if True else falseaction() trueaction called 0
- myelin 18y agoThe danger here is that this will fall through to the falseaction if trueaction returns a false result ("", False, 0, None, [], {}, etc). For example, this will evaluate to "etc": True and "" or "etc" So people started doing this instead, as [False] is still 'true' (non-empty lists are 'true' in Python): (condition and [trueaction] or [falseaction])[0] ... which is a bit crufty. So this was added: trueaction if condition else falseaction
- thomasmallen 18y agoAh, that is much better. I've been learning from Dive Into Python which I know is a tad dated, and Pilgrim (sort of) endorses the and...or method.