Today’s anonymous submitter is an experienced Python developer. Their team is significantly less experienced. In the interests of training, someone suggested, “Perhaps we should buy books for everyone.” Our submitter was handed a stack of possible books, and asked to pick the best one to help the team mature.

One book spent some time discussing types, and the conversion between them. By way of example, it provided a handy method which would turn a string into a floating point number:

def str_int(s):
    val = "%.2f" % profit
    return float(val)

According to the book, this method turns a string into a float, which is why it’s called str_int.

"%.2f" % profit is one of several Python string formatting conventions, and it will take the contents of the variable profit and substitute them where the % appears in the string. In this case, it will be formatted as a floating point with two decimal places. Oh, but wait a moment, the .2f format token requires whatever is being substituted in actually be a floating point value, so the contents of profit couldn’t possibly be a string, or this would fail.

Which, of course, brings us to the largest problem with this code. profit is not the parameter passed in. The parameter passed in is s. s is not used in the method. profit is not declared anywhere in this scope, and according to our submitter, wasn’t declared in any scope.

What this method actually does is crash. What it means to do is take the contents of a floating point variable, truncate it to two decimal places, and then returns it as a float, after taking a round-trip through a string. Which is not the best way to do this in the first place, and it certainly isn’t even the simplest.

I suspect the variable names betray the author’s actual goal for the book: not education, no the respect of their peers, but simply put: profit. The errors in this volume mean that they can work up a second edition, which both corrects these and adds entirely new errors, to promote the third edition!

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!