reference
3 min read
·
lesson 21 of 60 in Errors
TabError: inconsistent use of tabs and spaces
1 · The lesson
readWhat 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 raisesTabError. 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 indentationThe 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.pyIn 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=4and:set listto 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".
Related errors
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
- All Python errors: the full index, by type and by when it happens.
- Functions: where indentation matters most often.
- Style and PEP 8: for the four-spaces convention.
- cheat-syntax-errors: fast lookup for parser-level failures.
Found this useful? Share it with a friend who’s learning Python.