PythonMastery
reference 3 min read · lesson 21 of 60 in Errors

TabError: inconsistent use of tabs and spaces

1 · The lesson

read

What this error means

Python uses indentation to mark where blocks start and end. If one line in a block is indented with a tab and another with spaces, Python cannot reliably tell whether they are at the same level. Instead of guessing, the parser rejects the file and raises TabError. This is a subclass of IndentationError, which in turn is a SyntaxError, so it is raised before any of your code runs.

When you see it

text
  File "script.py", line 4
    return total
                ^
TabError: inconsistent use of tabs and spaces in indentation

The caret rarely points at the real cause. The tab that causes the problem is usually on a line above the one Python reports.

Why it happens

You opened a file that uses one indentation style in an editor configured for the other, pressed Enter, and your editor inserted the wrong character. Pasting code from a webpage, a Stack Overflow answer, or a colleague's editor is the most common way this happens. Older Python 2 code is also a common source, because Python 2 accepted mixed tabs and spaces more often.

How to fix it

Pick one style (four spaces, as PEP 8 recommends) and convert the whole file:

bash
python -m tabnanny script.py

tabnanny prints the line number and the text of the inconsistent line. To turn the tabs into spaces and save the result as a new file:

bash
# expand tabs to 4 spaces and write the result to a new file
python -c "import sys; sys.stdout.write(open('script.py').read().expandtabs(4))" > script.fixed.py

In your editor, set "indent with spaces, tab size 4" and turn on "show whitespace" so you see the problem:

  • VS Code: "editor.insertSpaces": true, "editor.detectIndentation": false, "editor.renderWhitespace": "all".
  • PyCharm: Settings -> Editor -> Code Style -> Python -> "Use tab character" off.
  • vim: :set expandtab tabstop=4 shiftwidth=4 and :set list to visualise tabs as ^I.

To see whitespace from the terminal:

bash
cat -A script.py    # tabs show as ^I, line ends as $

When you'd see this in real code

  • You copied a function from a blog post. The blog used tabs, but your project uses spaces.
  • You opened a Python 2 module in a modern editor that silently inserted spaces on new lines.
  • Two people on a team use different editor defaults and neither turned on "show whitespace".
  • IndentationError: unexpected indent: the indentation uses the same character throughout, but the level is wrong.
  • IndentationError: expected an indented block: a : opens a block but nothing is indented after it.
  • SyntaxError: any other parser failure.

See Also

Found this useful? Share it with a friend who’s learning Python.