python / python/cpython

chapter 8.3 in python errors-tutorial: update exception order code example for clarification

オープン
#136,228 コメント 3 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

docs
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Documentation

The errors tutorial, chapter 8.3 contains an example that could be improved, as the highlighted subjects (exception ordering and matching) are not that easy to follow: https://docs.python.org/3/tutorial/errors.html

The issue was discussed here:
https://discuss.python.org/t/exception-tutorial-confusion/97456

Original:
A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes (but not the other way around — an except clause listing a derived class does not match instances of its base classes). For example, the following code will print B, C, D in that order:

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.

Suggested Update
Code examples created by Guido van Rossum, see https://discuss.python.org/t/exception-tutorial-confusion/97456/5.
A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes (but not the other way around — an except clause listing a derived class does not match instances of its base classes).

For example, the following code will print B, C in that order:

class B(Exception):
    pass

class C(B):
    pass

for cls in [B, C]:
    try:
        raise cls()
    except C:
        # Matches C but not B.
        print("C")
    except B:
        # Matches B; not reached for C.
        print("B")

Note that if the except clauses were reversed (with except B first), it would have printed B, B — the first matching except clause is triggered, like in the following example:

for cls in [B, C]:
    try:
        raise cls()
    except B:
        # Matches B and C both.
        print("B")
    except C:
        # Not reached (the previous clause ate B and C)
        print("C")
Linked PRs
  • gh-136257

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンク先のドキュメントページにあるエラーに関するチュートリアルの第8.3章を読み、提案されている明確化についての議論を確認してください。現在の例外の順序に関する例と、提案された例を比較してください。この章がマッチングと最初に一致したものが優先される順序を明確に示せるようになれば、作業は完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
documentation
issue の種類
ドキュメント
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。