MeWrite Docs

AssertionError

Pythonでassert文の条件が失敗した場合に発生するエラー

概要

AssertionError は、Pythonの assert 文の条件が False と評価された場合に発生する例外です。デバッグやテストで使用されます。

エラーメッセージ

AssertionError
AssertionError: Expected 10, got 5
AssertionError: List should not be empty

原因

1. 条件がFalse

1
2
x = 5
assert x == 10  # AssertionError

2. 空のコレクションチェック

1
2
items = []
assert items  # AssertionError(空リストはFalsy)

3. 型チェック

1
2
value = "hello"
assert isinstance(value, int)  # AssertionError

解決策

1. メッセージを追加

1
2
3
x = 5
assert x == 10, f"Expected 10, got {x}"
# AssertionError: Expected 10, got 5

2. 本番環境ではassertを使わない

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# assertは最適化モード(python -O)で無視される

# NG: 本番コードでassert
def withdraw(amount):
    assert amount > 0  # -O で無視される

# OK: 明示的なチェック
def withdraw(amount):
    if amount <= 0:
        raise ValueError("amount must be positive")

3. pytestでの使用

1
2
3
4
5
# pytest はassertを拡張して詳細なエラーを表示
def test_addition():
    assert 1 + 1 == 3
    # AssertionError: assert 2 == 3
    #  +  where 2 = 1 + 1

4. カスタム例外に置き換え

1
2
3
4
5
6
7
8
class ValidationError(Exception):
    pass

def validate_age(age):
    if not isinstance(age, int):
        raise ValidationError("age must be an integer")
    if age < 0:
        raise ValidationError("age must be non-negative")

5. 型ヒントとmypyを使用

1
2
3
4
5
def greet(name: str) -> str:
    return f"Hello, {name}"

# mypyが型エラーを検出
greet(123)  # error: Argument 1 has incompatible type "int"; expected "str"

assertの適切な使用場面

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# 1. 内部の不変条件チェック
def binary_search(arr, target):
    assert arr == sorted(arr), "Array must be sorted"
    # ...

# 2. 開発中のデバッグ
def process(data):
    result = transform(data)
    assert result is not None  # 開発中のみ
    return result

# 3. テストコード
def test_user_creation():
    user = create_user("John")
    assert user.name == "John"
    assert user.id is not None

関連エラー

関連エラー

Python の他のエラー

最終更新: 2025-12-17