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

TabError: inconsistent use of tabs and spaces

1 · The lesson

read

What this error means

Python uses indentation to delimit blocks. 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. Rather than guess, the parser refuses the file and raises TabError. This is a subclass of IndentationError, which in turn is a SyntaxError, so it fires before your code runs at all.

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 culprit — the offending tab is usually on a line above the one Python complains about.

Why it happens

You opened a file that uses one indentation style in an editor configured for the other, hit return, and your editor inserted the wrong character. Pasting code from a webpage, Stack Overflow answer, or a colleague's editor is the classic vector. Older Python 2 code is also a common source — tabs were tolerated more freely back then.

How to fix it

Pick one style — four spaces, per PEP 8 — and convert the whole file:

bash
python -m tabnanny script.py

tabnanny prints the exact line and column of the inconsistency. To rewrite tabs as spaces in place:

bash
# expand tabs to 4 spaces, write back
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 actually see this in real code

  • You copied a function from a blog post; the blog used tabs, 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 is at least consistent in character, but the level is wrong.
  • IndentationError: expected an indented block — a : opens a block but nothing is indented after it.
  • SyntaxError — any earlier parser failure.

See Also