Mira was trawling through some old Python code. This particular block of code needed to load some data from JSON. The data was an array, and the code needed to know how long the array was.
Python has a handy len
function that does this on anything enumerable. If our developer had used len
, we'd be looking at different code today.
This was their approach:
tdata = json.load(html)
j = -1
test = True
while test:
try:
j = j+1
tdata[j]
except:
test = False
Whoever wrote this "must have been drunk," writes Mira. Certainly, they were under the influence of something.
This code loops while test
is true. Inside the loop, it increments j
, and then tries to access the element of the array at j
. If this succeeds, the loop continues. If it throws an exception (most likely because we've run off the end of the array), the code sets test
to False
, which causes us to exit the loop on the next iteration.
It's not just that they're using exceptions for flow control that bothers me, though that's the core WTF. But they found a way to do pretty much every other thing wrong. They start with j
at -1
, and then pre-increment, which isn't wrong but is unconventional. They could put the whole loop in an exception handler, or use a break
in the except
clause. Or they could have just used len
, which would have made all this code go away.