最終更新:2021-08-13 (金) 17:10:24 (949d)
Python/with
https://docs.python.org/ja/3/reference/compound_stmts.html#the-with-statement
with EXPRESSION as TARGET: SUITE
例
- with構文を使うとファイルの読み込みで必要なclose処理を省略することが出来ます
with open("sample.txt", "r") as f: print(f.read())
仕組み
動作
- 以下のコード:
with EXPRESSION as TARGET: SUITE
- これは次と等価です:
manager = (EXPRESSION) enter = type(manager).__enter__ exit = type(manager).__exit__ value = enter(manager) hit_except = False try: TARGET = value SUITE except: hit_except = True if not exit(manager, *sys.exc_info()): raise finally: if not hit_except: exit(manager, None, None, None)