What is the “inconsistent use of tabs and spaces in indentation” error and why is it caused?

Asked by Satyam[1]

Tabs and spaces are two different characters which are rendered as whitespace on screen. The problem is that there is no agreement on how wide a tab character must be, so some editors show it as occupying as much space as 8 spaces, some show it as occupying width of 4 and some 2, and it?s also configurable.

When you indent in python, python just expects that indentation in first line should be the same as indentation in rest of the lines, be it 4 spaces, 1 space, 1 tab, or whatever.

So when you code and one line is indented with a tab and another with spaces, python gives error, despite the fact that visually in the editor it looks fine (but it won?t look fine anymore if you change the width of a tab and double it, now it will look like the tab lines are indented two levels).

Hence it is suggested that you use either only tabs or spaces. Though it?s not really possible to do this when editing someone else?s code because we don?t know what they?ve used.

One way to combat this error is to go to the settings of your text editor and enable the ?convert tabs to spaces? feature which automatically replaces the tab character with n space characters, n being the tab width your editor uses.

In the python IDLE editor, you may use Edit > Untabify Region to convert any tabs to spaces.

Footnotes

1: The question was asked in a forum. I?ve copied the answer that I gave there into this post with minor edits.

21