CodeSOD: Changing the Type of Newbie
Today's story isn't really a WTF. No, Phil R was mentoring a new developer, and as such, Phil was sending some simple, easily scoped Python tasks over to that developer. After a few really low hanging fruit, Phil gave the Newbie a trickier one. The contact_type field was currently a string. That was a mistake, and it needed to be changed to a number. The change would involve a whole bunch of find-and-replace, but mostly it was just changing strings like '07' into 7.
Newbie trotted off, and found this code block:
if contact_type in ('01', '05', '07'): priority_flag = True
No problem, right? Simple task, just make those integers. Newbie did, and repeated the task in a few places, ran the unit tests, and was happy with the results. But that wasn't the only change they needed to make before the feature was implemented: one of the codes was incorrect. contact_type 7 should actually be a 9. Newbie made that change, and was rewarded with a syntax error they didn't understand: invalid token. So they went to Phil for some help.
Now, a I expect a lot of you have already figured out the punchline here, but let's retrace Newbie's steps. How do you turn '01' from a string, into a number, with the minimal change made? Why, you just strip the 's off.
if contact_type in (01, 05, 07): priority_flag = True
This passes the unit tests just fine. It's not technically even wrong, but it's doing something Newbie didn't even know they should be on the lookout for. So when they did this, it failed:
if contact_type in (01, 05, 09): priority_flag = True
"How," pleaded Newbie, "can just changing a digit create a syntax error?"
The leading 0 declares a number as octal. 09 is not a valid octal digit.
Now, Phil was able to quickly explain what went wrong, and it became a nice learning experience for the Newbie. They fixed the code, completed the work, created a merge request, and Phil and a few other developers reviewed it. Newbie stuck around, and eventually stopped being the Newbie, and became the old-hand, mentoring the Newbies that came after.
[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!