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.

4 thoughts on “Today’s Python funny: C style increment operator fails silently

  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.


  2. this increment thing for python is fucked up.
    any function to do that ?
    python has a range() but no relating how with ++
    ++n , n+=1, n++, n+, +n, etc…
    error,error… UnboundLocalError
    i dont want to mess with java c++ and other bullshit stuff.


  3. “Python doesn’t support any increment operator”

    It has both an increment and decrement operator :

    variable += n
    variable -= n


    • Paul, “+= n” or “-= n” aren’t increment (go to the next item) or decrement (go to the previous item). If you’re dealing with integers, you can increment and decrement because you know what those next values are (plus or minus 1). But for anything other than an integer, += and -= don’t really count as incrementing and decrementing (though they’re useful).


Comments are closed.