IndentationError: unexpected indent - 12 Causes and Fixes in Python
IndentationError: unexpected indent is Python refusing to compile your file at all: one line starts further to the right than the line above it, and nothing on that previous line opened a new block. The compiler never runs a single statement, so nothing you print or log inside the file will help you - the fix is always in the whitespace of the line the traceback names.
The message is narrow and that is good news. It does not mean "your indentation is messy somewhere"; it means the tokenizer emitted an INDENT token at a point where the grammar expected a statement at the same level as the previous one.
This page gives you the one-line fix first, then 12 distinct ways to get here - stray spaces, a commented-out if, a decorator, a closing bracket, a shell heredoc, exec on an indented string - each with a reproduction, the corrected lines, and a command that proves it is gone. If your case matches none of them, use the diagnostic checklist.
| Error | IndentationError: unexpected indent |
|---|---|
| Where it happens | Python 3.x (and 2.7) - raised at compile time by CPython's tokenizer, before any code executes. Appears when running a script, importing a module, pasting into the REPL, or compiling in CI. |
| What it means | A line is indented more than the statement above it, but that statement did not end in a colon, so no new block was open to receive it. |
The Fast Fix
Open the file at the line number in the traceback and delete the leading whitespace so the line sits at the same column as the statement above it.
# before - line 2 is indented, line 1 opened nothing
total = 0
total += 1
# after - both statements at column 0
total = 0
total += 1
Indentation is only legal after a line ending in : (if, for, while, def, class, try, except, with, else, elif, match, case). If the line above yours has no colon, the indent is wrong - not the line above.
Confirm with a compile-only run, which prints nothing on success:
python -m py_compile app.py
What Is Actually Causing It
Jump to your case
- 1. Stray leading spaces on a top-level statement
- 2. A line inside a block indented deeper than its siblings
- 3. Pasted code kept the leading whitespace of its source
- 4. You commented out or deleted the block header
- 5. Indentation used to continue an expression instead of brackets
- 6. An indented def or class after a decorator
- 7. Indented line after a one-line (inline) suite
- 8. Continuation indent kept after the closing bracket
- 9. A tab inserted at the start of a top-level line
- 10. Pasting an indented block into the interactive REPL
- 11. Indented Python inside a shell heredoc or CI run block
- 12. exec or compile on an indented source string
1. Stray leading spaces on a top-level statement
Reproduce it
# app.py
import os
print(os.getcwd())
File "app.py", line 4
print(os.getcwd())
IndentationError: unexpected indent
Why it happens — The module body is a block at column 0. import os did not end in a colon, so no nested block was opened, and the two spaces in front of print make the tokenizer emit an INDENT the grammar cannot place.
The fix
import os
print(os.getcwd())
Changed: removed the two leading spaces so print starts at column 0 like import.
Confirm it worked — python -m py_compile app.py exits silently, and python -c "import ast;ast.parse(open('app.py').read())" raises nothing.
2. A line inside a block indented deeper than its siblings
Reproduce it
def totals(rows):
count = 0
for row in rows:
count += row
return count
Why it happens — The first statement of a block sets that block's indentation width - here 4 spaces. Every later statement in the same block must match it exactly; for at 8 spaces looks like the start of a nested block, but count = 0 is not a block opener.
The fix
def totals(rows):
count = 0
for row in rows:
count += row
return count
Changed: for dedented to 4 spaces to match count = 0; its body stays one level deeper at 8.
Confirm it worked — Run python -m flake8 app.py (or pycodestyle app.py) - the E999 IndentationError and E117 over-indented reports both disappear.
3. Pasted code kept the leading whitespace of its source
Reproduce it
# pasted from a docs page where the snippet sat inside a function
import json
data = json.loads("{}")
print(data)
Why it happens — Documentation and Stack Overflow answers often show a fragment that was nested in a function or class. The paste carries that original indent level verbatim, which is meaningless in your file because the enclosing def came along as prose, not code.
The fix
import json
data = json.loads("{}")
print(data)
Changed: stripped the inherited 4-space prefix from every pasted line, keeping their relative depth.
Confirm it worked — Select the pasted region and dedent it in one keystroke (Shift+Tab in VS Code / PyCharm), then python -m py_compile app.py. If nothing is left to dedent, the paste is clean.
4. You commented out or deleted the block header
Reproduce it
# if debug:
print("state:", state)
print("done")
Why it happens — A # comment is invisible to the tokenizer - it produces no block opener. Commenting out if debug: or deleting a for line while keeping its body leaves an orphaned indented suite.
The fix
if debug:
print("state:", state)
print("done")
Changed: restored the header. To really disable the block, comment out its body too, or replace the header with if False:.
Confirm it worked — git diff the file: every surviving indented line should trace up to a live line ending in :. Then python -m py_compile app.py.
5. Indentation used to continue an expression instead of brackets
Reproduce it
total = price
+ tax
+ shipping
Why it happens — Python has no implicit statement continuation. total = price is a complete statement, so the next line is parsed as a new one - and it is indented, which is illegal. Only an open bracket or a trailing backslash continues a logical line.
The fix
total = (
price
+ tax
+ shipping
)
Changed: wrapped the expression in parentheses, so the indented lines are inside an open bracket and whitespace stops mattering.
Confirm it worked — python -c "import app; print(app.total)" prints a number instead of raising, confirming the three terms became one expression.
6. An indented def or class after a decorator
Reproduce it
@app.route("/health")
def health():
return "ok"
Why it happens — A decorator is not a block opener - it is a prefix of the same statement as the def that follows, so the def must sit at the decorator's own column. The indent makes the tokenizer open a block the grammar will not accept.
The fix
@app.route("/health")
def health():
return "ok"
Changed: def aligned with @app.route; only the function body is indented.
Confirm it worked — python -c "import app; print(app.health)" prints a function object, proving the decorator bound to it.
More causes (6 remaining)
7. Indented line after a one-line (inline) suite
Reproduce it
if ready: run()
cleanup()
Why it happens — Writing the body on the same line as the colon closes the suite immediately - there is no block left open on the next line. cleanup() is then a top-level statement with a stray indent.
The fix
if ready:
run()
cleanup()
Changed: moved run() onto its own indented line so both calls live in the same real block.
Confirm it worked — Set ready = False and run the file: neither run() nor cleanup() executes, which proves both are inside the if.
8. Continuation indent kept after the closing bracket
Reproduce it
config = dict(
host="localhost",
port=5432,
)
connect(config)
Why it happens — Inside brackets, indentation is ignored; the moment ) closes the call, normal indentation rules resume at the statement's own column. The editor's autoindent often leaves the continuation level behind on the next line.
The fix
config = dict(
host="localhost",
port=5432,
)
connect(config)
Changed: connect(config) moved back to column 0, matching config = dict(.
Confirm it worked — python -m py_compile app.py is silent, and black --check app.py reports the file unchanged.
9. A tab inserted at the start of a top-level line
Reproduce it
import sys
print(sys.version)
print("ready")
Why it happens — The last line begins with a tab character, which the tokenizer counts as indentation just like spaces. Because the previous line opened no block, any indent at all - tab or space - is rejected here.
The fix
import sys
print(sys.version)
print("ready")
Changed: deleted the leading tab. Configure the editor to insert spaces so it cannot come back.
Confirm it worked — cat -A app.py shows no ^I at line starts (on Windows: Select-String "t" app.pyreturns nothing), andpython -m py_compile app.py` is silent.
10. Pasting an indented block into the interactive REPL
Reproduce it
>>> x = 1
File "<stdin>", line 1
x = 1
IndentationError: unexpected indent
Why it happens — At the >>> prompt the interpreter is at top level and accepts no leading whitespace. Pasting a snippet that was nested inside a function sends its indent along with it.
The fix
# paste without the inherited indent, or wrap it so the indent is legal
def demo():
x = 1
return x
Changed: either strip the indent before pasting, or paste a complete def/if whose body legitimately owns that indent.
Confirm it worked — The prompt returns to >>> (or ... for an open block) without an error. For multi-line pastes, use python -i script.py or IPython's %paste, which handle leading whitespace.
11. Indented Python inside a shell heredoc or CI run block
Reproduce it
if [ -f data.csv ]; then
python - <<'PY'
import csv
print(sum(1 for _ in csv.reader(open("data.csv"))))
PY
fi
Why it happens — The two spaces that make the YAML or shell block readable are part of the heredoc payload, so Python receives a file whose first statement is indented. Quoted <<'PY' passes bytes through untouched - it does not strip whitespace.
The fix
if [ -f data.csv ]; then
python - <<'PY'
import csv
print(sum(1 for _ in csv.reader(open("data.csv"))))
PY
fi
Changed: Python lines moved to column 0 inside the heredoc. Keeping a tab-indented style instead requires <<-'PY', which strips leading tabs only, not spaces.
Confirm it worked — Run the shell snippet locally; it prints a row count. Or dump what Python actually gets: replace python - with cat and check that no line starts with whitespace.
12. exec or compile on an indented source string
Reproduce it
def build():
src = """
value = 2 + 2
print(value)
"""
exec(src)
Why it happens — The string literal keeps the indentation you used to keep the source file readable. exec compiles that text as a module body, where the leading 4 spaces are an unexpected indent - the error is raised at runtime by the inner compile, not by your file.
The fix
import textwrap
def build():
src = textwrap.dedent("""
value = 2 + 2
print(value)
""")
exec(src)
Changed: textwrap.dedent strips the common leading whitespace before exec sees the text.
Confirm it worked — print(repr(src)) - every line should start right after a \n. Then call build(); it prints 4.
## None of Those? Narrow It Down
- Read the line number and filename from the traceback, not from your editor's cursor - Python names the first offending line, and everything after it is unparsed. If the filename is
<stdin>or<string>, the problem is a REPL paste or anexec/compilecall, not a file on disk. - Look at the line immediately above the reported one, ignoring blank lines and comments. If it does not end in
:, the indent on the reported line is unconditionally wrong - delete it. If it does end in:, the reported line is over-indented relative to that block's first statement. - Check whether the line above is inside open brackets. Count unclosed
(,[,{upward: if a bracket closed just before your line, the editor likely left the continuation indent behind (cause 8). - Reveal whitespace (VS Code: View > Render Whitespace; or
cat -A file.py). A^Ior an odd column count tells you it is a tab or an off-by-one space rather than a logical nesting mistake. - Run
python -m tabnanny file.py. Output means the file mixes tabs and spaces ambiguously - normalise the whole file before chasing individual lines. Silence rules tab/space ambiguity out. - Search the file for commented-out block headers:
grep -n '^\s*#.*:\s*$' file.py. A commentedif/for/trydirectly above an indented suite is cause 4. - Re-indent only the reported region with an autoformatter you can undo:
black --diff file.py. Black cannot parse a file with this error, so if it reports a parse failure at the same line, the indent is structural - a human has to decide which block the line belongs to. - Compile the whole tree to catch the next one in the same file:
python -m compileall -q .. Each run surfaces exactly one indentation error, so repeat until it is silent.
Why This Error Exists At All
Most languages delimit blocks with braces and treat whitespace as decoration. Python made the opposite trade: indentation is the block structure. That means the tokenizer has to turn columns into tokens. It keeps a stack of indentation levels; when a logical line starts deeper than the top of the stack it pushes a new level and emits an INDENT token, and when it starts shallower it pops levels and emits DEDENT tokens. The parser then consumes INDENT/DEDENT exactly the way a C parser consumes { and }.
IndentationError: unexpected indent is what you get when that INDENT arrives and the grammar has no rule for an opening brace at that position. Only a handful of constructs - the compound statements ending in a colon - are followed by a rule that accepts INDENT. Everything else expects the next statement at the same level. So the message is literally "I produced an opening brace for you and there is no statement here that can take one." This is also why the error fires before your program runs, and why a print or a breakpoint earlier in the file tells you nothing: tokenizing happens in full before the first bytecode executes.
Seeing that stack machine makes the whole family legible. IndentationError: expected an indented block is the mirror image: a colon promised an INDENT and none came. unindent does not match any outer indentation level is a DEDENT that landed between two levels on the stack rather than on one of them - the reason you cannot close a block halfway. TabError: inconsistent use of tabs and spaces in indentation is the tokenizer refusing to guess a column at all, because the line's depth would differ depending on whether a tab counts as 1 or 8 columns. Four different messages, one mechanism: a stack of columns, pushed and popped per line. Once you ask "what did the tokenizer push, and what was legal there?" instead of "is my spacing pretty?", you fix these in seconds.
Stop It From Coming Back
- Set your editor to insert spaces, 4 per indent, and commit an
.editorconfigwithindent_style = space,indent_size = 4,insert_final_newline = trueso every contributor's editor agrees before the first keystroke. - Run
black(orruff format) on save. A formatter normalises every continuation indent and closing-bracket column, which eliminates causes 2, 5 and 8 as a class. - Add
flake8orruffto pre-commit and do not silence theE1family -E101(mixed indentation),E111(indent not a multiple of four),E117(over-indented) catch the near-misses that are legal Python but one keystroke from this error. - Add
python -m compileall -q .as the first step of CI. It is a byte-compile with no imports and no side effects, so a stray indent fails the pipeline in seconds instead of at deploy time. - Put
python -m tabnanny .in the same CI step to flag ambiguous tab/space mixes, which can read as correct in one editor and broken in another. - Wrap every generated or embedded source string in
textwrap.dedent()beforeexec,compile, or writing it to a file, and keep heredoc Python at column 0 even when the surrounding shell is indented.
Related Guides
Errors You Will Probably Hit Next
IndentationError: expected an indented blockIndentationError: unindent does not match any outer indentation levelTabError: inconsistent use of tabs and spaces in indentation
Jump to the line the traceback names, then read the line above it: if it does not end in a colon, your indent has nothing to attach to and must go; if it does, you are one level too deep for that block. Every variant of this error - stray spaces, a commented-out header, a decorator, a closed bracket, a heredoc, an exec string - reduces to that one question. Let a formatter own your columns and a compile step own your CI, and the question stops coming up.
댓글
댓글 쓰기