I'm porting an Excel-style formula parser from Python to Go and came across this comment in the function definition of the token stack:
def token(self):
# Note: this uses Pythons and/or "hack" to emulate C's ternary operator (i.e. cond ? exp1 : exp2)
return ((len(self.items) > 0) and [self.items[len(self.items) - 1]] or [None])[0]
I'm not really sure what the implications are of this, having only limited Python experience. I was going to attempt to literally translate as much of the code as possible and then debug later but as the author thought it important enough to warrant the comment, I feel like I should research this before I write anything.
I know what the ternary operator is, and I know it's been called unsafe to use the above over if statements in Python but I think it's been left in to exploit this. Could someone with a better knowledge of Python explain to me why someone would use this so-called hack over the recommended way so I know how to emulate its behaviour?
The full Python solution can be found here.