LoginSignup
0
1

More than 1 year has passed since last update.

Python 3.10 のwithステートメントで複数のオブジェクトを扱う

Posted at

Python 3.10 での with ステートメントに関する仕様変更

Pythonで open() 関数等と併用される with ステートメントは、カンマ区切りで指定することにより複数のオブジェクトを扱うことができる。(Python 3.1 以降)

with open("file1.txt", mode="w") as f1, open("file2.txt", mode="w") as f2:
    f1.write("This is file1")
    f2.write("This is file2")

Python 3.10 では、括弧で囲うことで複数行にまたがって書けるようになった。

with (
    open("file1.txt", mode="w") as f1,
    open("file2.txt", mode="w") as f2,
):
    f1.write("This is file1")
    f2.write("This is file2")

公式ドキュメントにも Python 3.10 で対応したことが明記されている。

バージョン 3.10 で変更: Support for using grouping parentheses to break the statement in multiple lines.

8. 複合文 (compound statement) — Python 3.10.4 ドキュメント

公式ドキュメントには Python 3.10 でサポートとあるが、実際には言語パーサーが更新された Python 3.9 以降で動作する。括弧による記述に対応していない Python 3.8 以前では、バックスラッシュ \ による行の継続で複数行の記述ができる。

括弧が使用できるメリットは、バックスラッシュによる行継続に頼らない記述が可能であること、Black 等のフォーマッタを利用した際にうまく自動整形されること、などがある。

参考文献

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1