how to reduce bugs due to incorrect indentation

Chris Angelico rosuav at gmail.com
Thu Feb 6 20:57:50 EST 2014


On Fri, Feb 7, 2014 at 12:20 PM,  <msustik at gmail.com> wrote:
> It would be possible to disable the Tab key completely and type in the spaces all the time. (It is much less likely that one would press the space bar accidentally four times or hold it down to get 4 spaces by mistake.)
>
> Unfortunately this means giving up the indentation help of the editor and that will slow down coding. It will also lead to many indentation mistakes during development (most of which will be caught right away however. Maybe a coloring of the background based on tab position could assist in this.
>

I don't know that it'd really help much anyway. You might reduce one
chance of making errors by hitting a single key, but at the cost of
stupid syntactic salt (indentation requires hitting a key four times?
No thanks), and your fingers would just get used to
whack-whack-whack-whack. No change.

You can spend all your time trying to warp your coding style around
preventing this bug or that bug from happening, or you can just
acknowledge that bugs WILL happen and handle them after the event.
(Hence, source control.) Suppose you come up with a solution to the
accidental-indentation problem. What are you going to do about this
one?

def foo(bar):
    if not bar: bat = [0]
    for x in bar:
        print(len(bar),x)

Now, why is your empty-list handling not working? Oh, there was a
typo. How are you going to deal with that? Well, you could bring in
C-style variable declarations; then you'd get an immediate error
('bat' is undeclared), but somehow I don't think most Python
programmers would prefer this :) Now personally, I do quite like
declared variables, because they allow infinitely-nested scoping, and
I find that feature worth the effort of declaring all my locals; but
it's a tradeoff, and I wouldn't go to that level of effort *just* to
catch typos in variable names. What if there had been a 'bat' at a
higher scope? Then the typo just means the code does something else
wrong. No fundamental difference.

There was a scheme posted to this list a little while ago to have
variable names shown in different colors, which might have helped. (I
disagree with the author's idea that similar names should be in
similar colors - I think that similar names should be in DISsimilar
colors, specifically to catch this sort of error. But anyway.) That's
a theory that might help... but it still might not. And what if your
error is in a literal string that later gets parsed? No, there's no
way that you can catch everything beforehand.

Bugs happen. Find 'em, fix 'em.

ChrisA



More information about the Python-list mailing list