11 / 90

Day 11: 例外と隔離環境

予期する例外だけを捕捉し、with と finally でクリーンアップを保証し、新しい仮想環境で「自分のマシンでは動く」故障を再現する。再生成より先に診断。 Retrieval and lower-new-content review are part of the 480-minute ledger.

Self-Directed Learning & Python 480 active minutes (8 hours focused study)
01 120 分

正確な例外処理と保証されたクリーンアップ

予測と観察した証拠を記録した後に限り、支援を利用してよい。

Prerequisites

前のアクティビティを完了していること。詰まった場合は記載の回復リンクを使う。

Learning Objective

ファイルのオープンが成功したときと FileNotFoundError を投げたとき、try・except・else・finally のどの節が実行されるかを予測して検証する。手動の close() を with ブロックに置き換え、裸の except が禁止される理由を説明する。

Instructions

try には危険な呼び出しを置く。except FileNotFoundError as e は予期する1種類の失敗だけを処理し、e.filename が見つからないパスを示す。else は例外が起きなかったときだけ実行され、finally は常に実行される。裸の except: は禁止。KeyboardInterrupt や本物のプログラムミスまで飲み込み、診断を当て推量に変えてしまうから。ファイルオブジェクトにとって with は定義済みのクリーンアップ動作であり、finally を不要にする。

Practice & Prediction Log

空の一時フォルダで作業する。このスクリプトを2回実行する:1回目は notes.txt が無い状態で、2回目は printf 'hi\n' > notes.txt で作成した後に。

try:
    f = open("notes.txt", encoding="utf-8")
except FileNotFoundError as e:
    print("cannot open", e.filename)
else:
    print("opened", f.name)
    f.close()
finally:
    print("cleanup")

各実行の前に、try / except / else / finally のどれが実行されるかと正確な出力を書き出す。その後 (1) else + f.close() の代わりに with ブロックでファイルを閉じるよう書き換え、ブロックの後で f.closed が True であることを示す。(2) 裸の except: が隠してしまうものを2つ挙げる。

Independent Mastery Criterion

成功時と失敗時にどの節が実行されるかを正確に述べ、else/close() パターンを with ブロックに正しく変換し、裸の except が隠すものを2つ挙げられる。

Authoritative Source Resources & Provenance

linking PSF License Version 2

The Python Tutorial: Errors and Exceptions

著者・提供機関: Python Software Foundation | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Sections 8.3–8.6 (handling exceptions, else, finally, cleanup actions)

検証バージョンと日付: Python 3.12 documentation; verified 2026-10-30

選定理由:

Primary reference for try/except/else/finally semantics and the with statement as predefined cleanup.

ソース前提知識:

安全フォールバック(オフライン回復性):

Every clause behavior in the lesson is demonstrated by runnable local snippets.

比較対象候補リソースと選定評価 (2)
MIT OCW 6.0001 Lecture on Exceptions ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid lecture treatment, but paced for a semester course and requires video viewing; the tutorial section matches the exercise scope directly.

Python Standard Library: Built-in Exceptions ↗ compared_alternative [PSF License Version 2]

Reference-style exception hierarchy listing rather than the tutorial narrative; retained as lookup material for the recovery drills.

02 120 分

故障クリニック:トレースバックから的を絞った修正へ

予測と観察した証拠を記録した後に限り、支援を利用してよい。

Prerequisites

前のアクティビティを完了していること。詰まった場合は記載の回復リンクを使う。

Learning Objective

不正なスコア行でクラッシュするスクリプトについて、トレースバックを下から読み、故障行と例外型を特定し、最小の修正を適用する:プログラム全体を包む捕捉ではなく、int() の周りだけの的を絞った except ValueError。

Instructions

トレースバックは呼び出しを古い順に並べ、最終行に例外型とメッセージを示す:ValueError: invalid literal for int() with base 10: 'x9'。その上のフレームは total += int(raw) の行を指す。まずその1つの悪い行だけでクラッシュを再現する。最も狭い修正は int(raw) だけを try/except ValueError で囲み、行番号を記録して続行すること。プログラム全体を except Exception で包むと無関係なバグを隠し、データエラーと誤報してしまう。

Practice & Prediction Log

空の一時フォルダでクリニック用のデータを作る:

printf 'ana,7\nbo,x9\ncy,5\n' > scores.csv

次を clinic.py として保存する:

total = 0
with open("scores.csv", encoding="utf-8") as fh:
    for lineno, line in enumerate(fh, start=1):
        name, raw = line.strip().split(",")
        total += int(raw)
print("total", total)

python3 clinic.py を実行し、トレースバックを下から読む。診断として、故障行・例外型・最も狭い修正を記録する。その後 clinic.py を直して最後まで実行させ、有効な行の合計とスキップした行番号を表示させる。

Independent Mastery Criterion

診断が故障位置と例外型を名指しし、例外階層に基づいて選んだ except 型が最も狭い正しい型である理由を説明し、スキップ報告を出してプログラムが完走することを示せる。

Authoritative Source Resources & Provenance

linking PSF License Version 2

Python Standard Library: Built-in Exceptions

著者・提供機関: Python Software Foundation | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Concrete exceptions and Exception hierarchy

検証バージョンと日付: Python 3.12 documentation; verified 2026-10-30

選定理由:

Normative hierarchy used to justify the narrowest correct except clause during diagnosis.

ソース前提知識:

安全フォールバック(オフライン回復性):

The clinic traceback is reproduced locally; help(ValueError) documents the hierarchy offline.

比較対象候補リソースと選定評価 (2)
W3Schools Python Exceptions ↗ compared_rejected_for_day11 [Proprietary]

Encourages broad except blocks; the clinic instead requires naming the exact hierarchy level.

The Python Tutorial: Errors and Exceptions ↗ compared_alternative [PSF License Version 2]

Friendlier first-pass narrative; the library reference was selected for the normative hierarchy the exercises name directly.

03 120 分

venv による隔離環境

予測と観察した証拠を記録した後に限り、支援を利用してよい。

Prerequisites

前のアクティビティを完了していること。詰まった場合は記載の回復リンクを使う。

Learning Objective

使い捨ての一時フォルダで python3 -m venv --without-pip .venv により仮想環境を作り、sys.executable でそのインタプリタが python3 と違うことを証明し、venv にだけインストールしたモジュールが python3 からは見えないことを示し、依存関係を requirements.txt に記録する。

Instructions

観察する違いがすべて自分で作ったものになるよう(自分のマシンについての思い込みにならないよう)、使い捨てフォルダの中だけで作業する。コマンドは Linux/macOS のシェル用(Windows ではインタプリタは .venv\Scripts\python.exe。ここでは未実行)。venv は activate しない:各インタプリタをパスで呼ぶ。

この作業専用の使い捨てシェル/セッションを使う。セットアップと以降のすべての手順は同じシェルで実行する。セットアップが1つでも失敗するとそのシェルは終了する。続行しない。新しいシェルではセットアップのブロックを再実行する。セットアップ後は、続行する前に pwd が $work を示すことを確認する。

work=$(mktemp -d) &&
cd "$work" &&
python3 -m venv --without-pip .venv || exit 1

以降の手順はすべて同じシェルで実行する。echo "$work" が何も表示しなければ、先にセットアップのブロックを再実行する。--without-pip により作成はオフラインで済み、新しい venv には標準ライブラリしか無い。sys.executable は実際に動いているインタプリタを示す。sysconfig.get_path('purelib') はそのインタプリタの site-packages フォルダ(インストール済みモジュールの置き場所)を示すので、そこに1ファイルのモジュールをコピーすることは、ネットワークもサードパーティパッケージも要らない手作りのインストールになる。これは学習用の近道で、pip の動作そのものではない。pip はインストールのメタデータ(.dist-info フォルダ)も書き込むので、この手作業のコピーは pip に記録されず、pip でアンインストールもできない。venv の pyvenv.cfg には include-system-site-packages = false とあり、venv はベースのインタプリタの site-packages を読まず、他のインタプリタも venv のものを読まない。依存はピン留めした行として requirements.txt に書き(認証情報は絶対に入れない)、.venv は決してコミットしない。終わったら:cd / && rm -rf "$work"。

Practice & Prediction Log

$work で、実行する前に各結果を予測する。ステップ1:どのインタプリタが動くか?

python3 -c "import sys; print(sys.executable)"
.venv/bin/python -c "import sys; print(sys.executable)"

ステップ2:作りたての venv は day11_helper をインポートできるか?

.venv/bin/python -c "import day11_helper"

ステップ3:1ファイルのモジュールを venv にだけインストールし、そこでインポートする:

site=$(.venv/bin/python -c "import sysconfig; print(sysconfig.get_path('purelib'))")
printf 'def label():\n    return "helper from the venv"\n' > "$site/day11_helper.py"
.venv/bin/python -c "import day11_helper; print(day11_helper.label())"

ステップ4:python3 はそれをインポートできるか?

python3 -c "import day11_helper"

ステップ5:隔離の証拠と、この venv に pip があるかどうか:

grep include-system-site-packages .venv/pyvenv.cfg
.venv/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)"
.venv/bin/python -m pip --version

ステップ6:練習用のピン留めを記録する(インストールはしない。pip とパッケージインデックスが必要になるため):

printf 'packaging==24.1\n' > requirements.txt
cat requirements.txt

ステップ2と4について診断を記録する:import 行を編集すべきか、環境を変えるべきか?

Independent Mastery Criterion

2つのインタプリタパスが違うことを証明し、作りたての venv で ModuleNotFoundError を再現し、モジュールを venv にだけインストールした後に python3 で再び再現し、pyvenv.cfg と sys.prefix から、venv と他のインタプリタが互いの site-packages を見られない理由を説明できる。

Authoritative Source Resources & Provenance

linking PSF License Version 2

The Python Tutorial: Virtual Environments and Packages

著者・提供機関: Python Software Foundation | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 12 (Virtual Environments and Packages; creating venvs, pip, requirements)

検証バージョンと日付: Python 3.12 documentation; verified 2026-10-30

選定理由:

Primary reference for python -m venv, interpreter isolation, and requirements files.

ソース前提知識:

安全フォールバック(オフライン回復性):

The drill needs no network: venv creation, sys.executable inspection, and ModuleNotFoundError reproduction all run offline.

比較対象候補リソースと選定評価 (2)
pip documentation ↗ compared_alternative [MIT]

Primary reference for pip commands, but the tutorial section covers the create-activate-install loop as one narrative better suited to beginners.

virtualenv documentation ↗ compared_alternative [MIT License]

Mature third-party environment tool with overlapping behavior; the stdlib venv tutorial was selected to avoid an extra dependency for first-time setup.

04 120 分

環境違いの診断ドリル

独立習得チェック(AI 支援なし)。

Prerequisites

前のアクティビティを完了していること。詰まった場合は記載の回復リンクを使う。

Learning Objective

制御された2つのインタプリタの一方でだけ ModuleNotFoundError で失敗するスクリプトを独力で診断し、sys.executable と find_spec の証拠および最小の環境修正を示す。さらにファイル読み取りを正確な except 節で包む。

Instructions

資料を見ずに(クローズドブックで)行う。このフィクスチャを正確に作る。依存を持つのが good の venv だけであることが保証される(Linux/macOS のシェル、ネットワーク不要、サードパーティパッケージ不要):

この作業専用の使い捨てシェル/セッションを使う。セットアップと以降のすべての手順は同じシェルで実行する。セットアップが1つでも失敗するとそのシェルは終了する。続行しない。新しいシェルではセットアップのブロックを再実行する。セットアップ後は、続行する前に pwd が $work を示すことを確認する。

work=$(mktemp -d) &&
cd "$work" &&
python3 -m venv --without-pip good &&
python3 -m venv --without-pip .venv &&
good_site=$(good/bin/python -c "import sysconfig; print(sysconfig.get_path('purelib'))") &&
printf 'def label():\n    return "report ok"\n' > "$good_site/day11_helper.py" &&
printf 'import day11_helper\nprint(day11_helper.label())\n' > report.py || exit 1

以降の手順はすべて同じシェルで実行する。echo "$work" が何も表示しなければ、先にセットアップのブロックを再実行する。症状:.venv/bin/python report.py は ModuleNotFoundError: No module named 'day11_helper' を投げるが、good/bin/python report.py は動く。課題1:両方のインタプリタから証拠を集め(どのインタプリタが動くか、day11_helper を見つけられるか)、診断を記録し、最小の修正を適用して、その後 .venv/bin/python report.py が report ok を表示することを示す。課題2:path を encoding="utf-8" で開く処理を try/except FileNotFoundError の中に置き、クラッシュする代わりに missing と e.filename を表示する read_text(path) を書く。終わったら:cd / && rm -rf "$work"。

Practice & Prediction Log

記録するもの:(a) 2つの sys.executable の値。(b) 各インタプリタが day11_helper を見つけられるか。(c) .venv/bin/python で再現した ModuleNotFoundError。(d) 診断の分類:コードの故障か環境の故障か。(e) 修正と、それが効いたことを示す出力。(f) 自分の read_text 関数と、no_such_file.txt に対するその出力。

Independent Mastery Criterion

独力で、診断が証拠に基づき(両方のインタプリタからの sys.executable と、find_spec または ModuleNotFoundError)、修正がその証拠で特定した原因に対処し report ok で証明され、ファイル読み取りがちょうど except FileNotFoundError を使う。

Authoritative Source Resources & Provenance

linking PSF License Version 2

The Python Tutorial: Virtual Environments and Packages

著者・提供機関: Python Software Foundation | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Section 12 (Virtual Environments and Packages; creating venvs, pip, requirements)

検証バージョンと日付: Python 3.12 documentation; verified 2026-10-30

選定理由:

Reference retained for the independent wrong-environment diagnosis assessment.

ソース前提知識:

安全フォールバック(オフライン回復性):

The assessment reproduces ModuleNotFoundError with the local interpreter only.

比較対象候補リソースと選定評価 (2)
pip documentation ↗ compared_alternative [MIT]

Reference for install commands if the learner chooses the install-based fix.

virtualenv documentation ↗ compared_alternative [MIT License]

Mature third-party environment tool with overlapping behavior; the stdlib venv tutorial was selected to avoid an extra dependency for first-time setup.