pythonにおけるwith as文の役割と意味

5731 ワード

簡単にまとめる
with as文の役割は主に以下の通りである:1、異常終了時の資源解放の問題を解決する;2、ユーザーがcloseメソッドを呼び出すことを忘れたことによる資源漏洩問題を解決する.つまり、with asの方法はサボりやすいプログラマーやいい加減なプログラマーに最適で、C/C++から来たプログラマーは資源の漏れやメモリの問題を体験したことが少なくありませんが、withas文は苦海からの解放を便利に助けることができます.
詳細:
公式ドキュメントのwith文の説明を見てみましょう.
The with statement:
The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows common try…except…finally usage patterns to be encapsulated for convenient reuse.
with文は、コンテキストマネージャによって定義された方法でプログラムをパッケージング実行する.これにより、一般的なtry...except...finallyモードの使用法がパッケージされ、繰り返し使用されます.
with_stmt ::=  “with” with_item (“,” with_item)* “:” suite
with_item ::=  expression [“as” target]
#     :
with item as target:

The execution of the with statement with one「item」proceeds as follows:with文を使用してitemプロセスを実行するには、次のようにします.
1、The context expression (the expression given in the with_item) is evaluated to obtain a context manager. コンテキスト式が検出され、コンテキストマネージャが取得されます.
2、The context manager’s exit() is loaded for later use. コンテキストマネージャのexit()メソッドは、後で使用するためにロードされます.
3、The context manager’s enter() method is invoked. コンテキストマネージャのenter()メソッドがアクティブ化(実行)されます.
4、If a target was included in the with statement, the return value from enter() is assigned to it. with文にターゲットが含まれている場合、enter()からの戻り値がバックグラウンドされます.
Note The with statement guarantees that if the enter() method returns without an error, then exit() will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 6 below. 注意、with文は、enter()メソッドがエラーを返さない場合、exit()は常に呼び出されます.したがって、ターゲットリストに割り当てられている間にエラーが発生した場合、スイート内で発生したエラーと同じとみなされます.次の手順6を参照してください.
5、The suite is executed. このプログラムは実行されます
6、The context manager’s exit() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to exit(). Otherwise, three None arguments are supplied. コンテキストマネージャのexit()メソッドが実行され、このグループのプログラムが予期せぬ終了をもたらした場合、このグループのプログラムのタイプ、戻り値、およびトレースフィードバックがファイルとしてexit()に渡されます.3つのパラメータが提供されていない場合、このプロセスは異なる結果をもたらします.
If the suite was exited due to an exception, and the return value from the exit() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with statement. このプログラムが予期せぬ終了を余儀なくされ、exit()メソッドによって得られた戻り値が偽である場合、予期せぬことが再提案されます.戻り値が真の場合、予期せぬことが隠され、プログラムは続行されます.
If the suite was exited for any reason other than an exception, the return value from exit() is ignored, and execution proceeds at the normal location for the kind of exit that was taken. このプログラムが予期せぬ終了でない場合、exit()からの戻り値は無視され、プログラムは通常の場所で実行に使用される終了タイプを処理します.
上記のコンテンツマネージャは主にwith申明で定義されたランタイムコンテンツ(runtime context)を管理するために用いられ、環境、状態とも言える.このマネージャはenter()メソッドとexit()メソッドの2つのメソッドを実装します.
enter()メソッドは、主にランタイムコンテンツ(runtime context)に入り、それに対応するオブジェクトを返します.このメソッドの戻り値は、context Managerを使用するwith文のas識別子の後にバインドされます.例を挙げます.
with open('text.txt') as file
    file.read()

コンテンツマネージャ(context manager)のenter()メソッドは、fileに値を付与したファイルオブジェクトを返します.
exit(exc_type,exc_val,exc_tb)メソッドは、この実行時のコンテンツまたは環境(runtime context)を終了し、途中で発生した異常を無視するかどうかを決定するためにブール値の変数を返すことです.途中でwith文の実行体に何か問題が発生した場合.対応する異常タイプ,値および遡及情報がこのメソッドに伝達され,異常がなければNoneに伝達される.異常入力があり、ブール値が真の場合、異常入力があるがブール値が偽の場合、異常は無視されます.コンテンツマネージャのポイントはtry...except...finallyの多重性を向上させることです.
プログラムを実行して出力結果をテストします
コンパイル環境:Python 3.6.2,Pycharm
class Test:
    def __enter__(self):
        print("this is in __enter__")
        return "enter_test"

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("this is in __exit__")


def test_funcion():
    return Test()


if __name__ == "__main__":
    with test_funcion() as test:
        print("The Test return value is", test)

実行結果
this is in __enter__
The Test return value is enter_test
this is in __exit__