5 ms·
Python 2.5 now lets you do: x = f(x) if a else g(y) f() and g() aren't evaluated till they're needed.
by andyn 19y ago
Python 2.5 now lets you do:
x = f(x) if a else g(y)
f() and g() aren't evaluated till they're needed.
- brlewis 19y agoThat syntax looks like it's intended to communicate that f(x) is the normal result, and g(y) is exceptional. I wouldn't want to use it unless that's what I intended to communicate. It also looks like you would need to put parens around the "if" expression if you were to use it within a more complex expression, e.g 2 + (f(x) if a else g(y)) + 3
- nostrademons 19y agoAnd before Python 2.5, people usually used this idiom: x = a and f(x) or g(y) If you know the idiom, I think this is more readable (conditional is on the left), though it has the drawback of using completely nonsensical keywords.
- Goladus 19y agoThanks, I didn't know that. That makes parenthesis optional unless you need to break precedence rules.