0

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.

leylandski
  • 448
  • 1
  • 3
  • 13
  • 4
    For this specific example the author used `and` and `or` as a poor-man's conditional expression (Python now has a proper conditional expression and the above should really be written as `self.items[-1] if self.items else None`). – Martijn Pieters Jul 13 '15 at 13:32
  • 5
    The quality of that piece of code is generally terrible, however, even without the conditional expression. It is returning the last `self.items` value if available, or `None` if not. `self.items and self.items[-1] or None` would have done too, except where `self.items[-1]` is a false-y value such as `0` or `''`, which is what the author tried to work around with the whole lists dance. – Martijn Pieters Jul 13 '15 at 13:33
  • So I don't need to worry about the fact that that 'hack' can give incorrect results under certain conditions being deliberately left because that's what the author intended? – leylandski Jul 13 '15 at 13:37
  • 2
    The author hacked a hack because the `and`..`or` hack can lead to incorrect results without such further messing about. Their version gives correct results but is unreadable and needlessly verbose. The version in my first comment is idiomatic Python and works correctly. – Martijn Pieters Jul 13 '15 at 13:42
  • Also see [Does Python have a ternary conditional operator?](http://stackoverflow.com/q/394809) – Martijn Pieters Jul 13 '15 at 13:43

0 Answers0