MeWrite Docs

IndentationError・TabErrorの原因と修正方法

概要

PythonでIndentationErrorやTabErrorが発生するのは、コードのインデント(字下げ)に不整合がある場合である。Pythonはインデントでブロック構造を定義するため、スペースとタブの混在や不正なインデントレベルがあると即座にエラーとなる。

エラーメッセージ

  File "example.py", line 4
    print("hello")
    ^
IndentationError: unexpected indent
  File "example.py", line 3
    return x + 1
                ^
IndentationError: unindent does not match any outer indentation level
  File "example.py", line 5
    print(result)
                 ^
TabError: inconsistent use of tabs and spaces in indentation

原因

  1. スペースとタブの混在: エディタの設定によってはタブ文字とスペースが混在し、見た目は揃っていてもPythonインタプリタが不整合と判定する。Python 3ではタブとスペースの混在はTabErrorとして明示的に検出される。

  2. 不正なインデントレベル: ブロック内のインデント量が前の行と一致しない。特にコピーペーストでコードを持ってきた場合や、異なるエディタで編集した場合に発生しやすい。

  3. ブロック開始後のインデント不足: iffordefclassなどの複合文の後にインデントされた本体がない場合。

  4. 不要なインデント: ブロック外でインデントが入っている行がある場合。

解決策

1. エディタの設定をスペース4つに統一する

ほとんどのPythonスタイルガイド(PEP 8)ではスペース4つを推奨している。エディタの設定を確認し、タブをスペースに変換する。

1
2
3
4
5
6
# 正しいインデント(スペース4つ)
def greet(name):
    if name:
        print(f"Hello, {name}")
    else:
        print("Hello, World")

VS Codeの場合、settings.jsonで以下を設定する:

1
2
3
4
5
{
    "editor.insertSpaces": true,
    "editor.tabSize": 4,
    "editor.detectIndentation": false
}

2. 既存ファイルのタブをスペースに一括変換する

1
2
3
4
5
# expandコマンドでタブをスペースに変換
expand -t 4 example.py > example_fixed.py

# Pythonのtabnanny モジュールでインデントをチェック
python -m tabnanny example.py
1
2
3
4
# autopep8で自動修正
# pip install autopep8
import subprocess
subprocess.run(["autopep8", "--in-place", "--aggressive", "example.py"])

3. 不正なインデントを手動で修正する

1
2
3
4
5
6
7
8
9
# NG: インデントレベルが不揃い
def calculate(x):
    result = x * 2
      return result  # IndentationError: unexpected indent

# OK: インデントを揃える
def calculate(x):
    result = x * 2
    return result

4. 空ブロックにはpassを使う

1
2
3
4
5
6
7
# NG: ブロック本体がない
def placeholder():
# IndentationError: expected an indented block

# OK: passで空ブロックを明示
def placeholder():
    pass

5. Pythonの -tt オプションでタブ混在を検出する

1
2
# Python 2の場合(Python 3ではデフォルトでTabErrorになる)
python -tt script.py

関連エラー

関連エラー

python の他のエラー

最終更新: 2026-03-20