削除された内容 追加された内容
編集の要約なし
Ef3 (トーク | 投稿記録)
→‎Python 3.12 の新機能: Python 3.12 の新機能
タグ: 2017年版ソースエディター
59 行
: [[/組込み関数|組込み関数]]{{進捗簡易|25%|2022-11-28}}
: [[/組込み型|組込み型]]{{進捗簡易|50%|2022-11-28}}
 
== Python 3.12 の新機能 ==
Python 3.12 には、いくつかの新機能が追加されています。以下にいくつかの新機能とそれらを使用するためのコード例を示します。
 
* Parenthesized context managers in with statements
Python 3.12 では、with ステートメントのコンテキストマネージャーに括弧を付けることができます。これにより、コンテキストマネージャーが複数の行にまたがっている場合に、より読みやすいコードを書くことができます。
 
;コード例:<syntaxhighlight lang=python3>
# Before Python 3.12
with open("file.txt", "r") as file1, open("file2.txt", "r") as file2:
# do something with file1 and file2
 
# With Python 3.12
with (open("file.txt", "r"), open("file2.txt", "r")) as (file1, file2):
# do something with file1 and file2
</syntaxhighlight>
 
*Pattern matching improvements
Python 3.10 で導入されたパターンマッチングには、Python 3.12 で改良が加えられました。例えば、以下のように | を使用して複数のパターンをマッチングすることができます。
 
;コード例:<syntaxhighlight lang=python3>
# Before Python 3.12
def my_function(x):
if isinstance(x, int):
# do something
elif isinstance(x, str):
# do something else
elif isinstance(x, list):
# do something else
else:
raise ValueError("Invalid argument type")
 
# With Python 3.12
def my_function(x):
match x:
case int:
# do something
case str:
# do something else
case list | tuple:
# do something else
case _:
raise ValueError("Invalid argument type")
 
</syntaxhighlight>
 
*New zoneinfo module for working with time zones
Python 3.9 で導入された zoneinfo モジュールは、Python 3.12 で改良が加えられました。これにより、タイムゾーンを扱うためのさまざまな機能が追加されました。
 
;コード例:<syntaxhighlight lang=python3>
# Before Python 3.12
import datetime
import pytz
 
tz = pytz.timezone("Asia/Tokyo")
now = datetime.datetime.now(tz)
 
# With Python 3.12
import datetime
import zoneinfo
 
tz = zoneinfo.ZoneInfo("Asia/Tokyo")
now = datetime.datetime.now(tz)
</syntaxhighlight>
 
{{stub}}
 
== 整理作業中 ==
64 ⟶ 130行目:
 
 
{{stub}}
[[Category:Python]]
[[Category:プログラミング言語]]