PromptHub
Python Beginner 10 views

Python TabError

The code uses inconsistent indentation by mixing tabs and spaces.

Explanation

TabError is a subclass of IndentationError that specifically occurs when Python encounters a mix of tabs and spaces for indentation. Python 3 strictly prohibits mixing tabs and spaces - it treats them as different indentation levels and raises an error. A tab is typically equivalent to 8 spaces, so mixing them creates ambiguous indentation. This error is common when code is edited in different editors with different settings.

Common Causes

  • Mixing tabs and spaces in same file
  • Different editor settings
  • Copy-pasting from different sources
  • No .editorconfig enforcing consistency
  • Auto-indent using wrong character

Solution

Configure your editor to use spaces instead of tabs (PEP 8 recommends 4 spaces). Enable "convert tabs to spaces" in your editor settings. Use the "show whitespace" feature to see invisible characters. Run autopep8 or black to auto-format and fix indentation. Check your .editorconfig file to enforce consistent indentation across your team.

Code Example

# Mixing tabs and spaces - TabError
def process():
    if True:
        print('spaces')  # 4 spaces
\tprint('tab')  # tab character - ERROR!

# Fix: use consistent indentation
def process():
    if True:
        print('spaces')  # 4 spaces
        print('also spaces')  # 4 spaces

# Check for mixed indentation
# In bash:
cat -A file.py | grep -n $'\t'  # find lines with tabs

# Or use Python's tabnanny
import tabnanny
tabnanny.check('file.py')  # reports files with mixed indentation

# Auto-fix with black
# pip install black
black file.py  # auto-formats entire file

# EditorConfig to enforce consistency
# .editorconfig:
[*]
indent_style = space
indent_size = 4

Error Information

Language

python

Difficulty

Beginner

Views

10

Related Errors