アサーション

assert 条件式, 説明

i = 10
assert i <= 9, "i is out of range. i: " + str(i)
# AssertionError: i is out of range. i: 10

↑のコードは↓と等価

if __debug__:
    if not i <= 9:
        raise AssertionError("i is out of range. i: " + str(i))
  • ビルトイン変数 __debug__ は、通常は True 、コマンドラインオプション(-O)で最適化が指定されたときは False。
  • コンパイル時に最適化が指定されても、アサーションのコードは省かれない。
  • スタックトレースに条件文が表示されるので、エラーメッセージに含む必要はない。
  • __debug__ に値を割り当てるのは不正。インタプリタが開始されるときに、__debug__ の値は決定される。

6. Simple statements — Python v3.1.5 documentation