I've recently become quite taken with conditional expressions in Python. Apparently some people consider it unpythonic and whether or not conditional/ternary expressions are even A Good Thing seems to be up for debate -- but I've been digging them lately.
x if C else y
So far I've noted there are two ways Python will appear to 'let' you use this syntax, though I only see a pointer to the first in its official docs, so I'm a little uncertain if the second method (which I've not used, yet) is considered a good practice or not.
The first, being:
myvariable = x if C else y ##also, "return x if C else y"
Seems fairly common; one finds it in JavaScript and Ruby and basically any other language where you'd be impelled to drop a one-liner instead of three lines of
if C:
myvariable = x
else:
myvariable = y
However, I do see that Python will let you 'get away' with a line such as this, without assigning anything:
foo() if C else bar()
I'm a fairly new programmer, really, and so I try to hesitate implementing the wrong tool for the job. This to me looks like an interesting method for controlling the flow of a program, if not the typical way for doing so. For example, if we get the high score on Stick's Asteroid's Clone v.001:
record_score() if currentscore > highestscore else display_scores()
I find it readable (others may not) and descriptive. However, in my non-exhaustive independent research of being able to use conditional expressions in a way besides assignment, I don't really see a whole lot of precedent for it. That leads me to think that one wouldn't really use it in this way in the first place, regardless of the language you're in, because it just isn't the right way to handle the state of your program.
Additionally, I recognize that the difference between a 'good' implementation of this and a 'bad' one may just be to make use of return
and reconsider the relevant code.
return record_score if currentscore > highestscore else display_scores ##and then the state machine takes over
That's fine too, but the question still stands in my mind if the suggested wording would ever be acceptable in the first place.
So I ask, is it even good practice to use conditional expressions apart from assignment? Or to put a finer point on it, is it acceptable to use it as a means of controlling the flow of a program?