SyntaxError vs IndentationError vs TabError in Python

When writing Python code, parsing errors halt program execution before the runtime begins. Python uses an exception hierarchy to categorize these parsing mistakes: SyntaxError represents general structural or grammatical rule violations, IndentationError is a specific subclass denoting improper block alignment, and TabError is a narrower subclass of IndentationError triggered by mixing tabs and spaces. Understanding the boundaries between these three exceptions allows developers to quickly isolate and resolve code formatting and parsing problems.

The Exception Hierarchy

In Python, these errors do not exist as independent, disconnected classes. Instead, they form a strict parent-child inheritance hierarchy:

SyntaxError
 └── IndentationError
      └── TabError

Because of this structure, every TabError is an IndentationError, and every IndentationError is a SyntaxError. However, the reverse is not true.

SyntaxError

A SyntaxError occurs when the Python parser encounters code that violates the core formal grammar of the language. The parser cannot tokenize or structure the code into an Abstract Syntax Tree (AST), making execution impossible.

Common causes include:

# Causes SyntaxError: invalid syntax
def calculate_total(a, b)
    return a + b

IndentationError

Because Python relies on whitespace to define code blocks instead of curly braces or keywords, indentation is part of the language's syntax. An IndentationError is a subclass of SyntaxError raised when the parser expects a block to begin or end, but the spacing does not match the logical flow of the code.

Common causes include:

# Causes IndentationError: expected an indented block after 'if' statement
if True:
print("Condition met")

TabError

A TabError is a specialized subclass of IndentationError. It occurs specifically when a file uses an inconsistent mix of tabs and spaces for indentation within the same block of code.

Python 3 strictly forbids mixing tabs and spaces for indentation in the same logical block because different text editors and environments interpret tab widths differently (e.g., 2, 4, or 8 spaces), which can obscure the true structural hierarchy of the program.

# Causes TabError: inconsistent use of tabs and spaces in indentation
def process_data():
    x = 10      # Indented with 4 spaces
    y = 20      # Indented with 1 tab
    return x + y

Comparison Summary

Error Type Direct Parent Cause Example Trigger
SyntaxError Exception General violation of Python grammar rules. Missing colon, unmatched parenthesis.
IndentationError SyntaxError Incorrect alignment or missing/unexpected indentation levels. Failing to indent inside a function body.
TabError IndentationError Mixing tabs and spaces within the same code block. Using spaces on one line and tabs on the next.