Two Ideas
1Feb/121

Today’s Python funny: C style increment operator fails silently

Where I work, much of our product is coded in Python, which despite much griping I think is a great language.

We've had a bug where an operation count was always reported as zero, even though the operation seemed to alter the filesystem. We've sort of shrugged, as it's an internal tool and it was doing what was required.

Today, a co-worker of mine found the bug: a piece of code was using a C-style increment operator.

Had the increment operator in question been variable++, this would have produced an error: Python doesn't support any increment operator; you write variable = variable + 1. This error would have prevented the program from running at all, and the bug would have been obvious.

Instead, the increment operator was a prefix rather than a suffix: ++variable.

In Python, a prepended plus is just a unary plus operator. It does, basically nothing. (Yes, that's not technically true, but it's effectively true in most cases.)

But, oddly, you can have two unary plus operators, which does double nothing! And runs without an error message! And, as a bonus, it looks to a C programmer as though it would increment a number.

Which would result in an operation count always equal to zero, no matter how many items you count.

Comments (1) Trackbacks (0)
  1. First reaction: What kind of C programmer does ++var; rather than var++; when they are just incrementing a value?

    Second reaction: Damnit, Python! Stop giving the haters excuses!

    Third reaction: Fascinating.


Leave a comment

(required)

No trackbacks yet.