The Daily WTF
Today’s anonymous submitter sends us a pile of code that exists to flummox us. It’s consfuing, weird, and I don’t understand it, even as I understand it. So we’re going to walk through this packet of Python in steps, to see if we can understand what’s going on.
First is this handy helper function, to turn a value into a number:
def to_number(s): try: if not s: return 0 number = float(s) return int(number) if number.is_integer() else number except (TypeError, ValueError): return s
This doesn’t start too badly. If the value is falsy (None, for example), return 0. If it has a value, though, turn it into a float. If the resulting float doesn’t have a decimal part, convert it into an integer. I’ve got some complaints about a method returning two different types, but I understand the urge.
But then we get to the exception handler. If, for
To read the full article click on the 'post' link at the top.