2021年11月9日火曜日

Python 3.10 の新機能

今回のバージョンはてんこ盛り。パターンマッチングはとりあえずでもいいので、目を通しておくべき。

■ 複数のwith
ネストさせずカンマ区切りで書けるようになった
with (open("file1") as file1, 
      open("file2") as file2,
      open("file3") as file3):
    print(file1.read(), file2.read(), file3.read())

■ パターンマッチング
対象となる変数がstringや int だったら他の言語のcase文のような感じで利用できる。
# dict の場合
import requests
pulls = requests.get("https://api.github.com/repos/python/cpython/pulls?state=all").json()

for pull in pulls:
    match pull:
        case {'state': 'open', 'number': number, 'title': title}:
            print("オープン:", number, title)
        case {'state': 'closed', 'number': number, 'title': title, 'closed_at': closed_at}:
            print("クローズ:", number, title, closed_at)

tuple, list にも使える。同じ長さやn番目の値を一致するかどうかの判定に使える。
独自のclass やそれらの型を含むdict, list でもOK

その他
case _: # ワイルドカード: 全てにマッチする
case Point(x, y) if x == y: # ガード: if でマッチ条件を追加する
case (Point(x1, y1), Point(x2, y2) as p2): # キャプチャ: ここにマッチした場合、2つ目の値はp2 として利用できる

どんなパターンがあるのか、PEPは一読しておいたほうがいいかも。
PEP 634 – Structural Pattern Matching: Specification
PEP 635 – Structural Pattern Matching: Motivation and Rationale
PEP 636 – Structural Pattern Matching: Tutorial
日本語でまとめられている
Python 3.10の新機能:「構造的パターンマッチ」とは


What’s New In Python 3.10
Python 3.10の新機能(その1) パターンマッチ

0 件のコメント:

コメントを投稿