ここ最近はPythonを使うことがほとんどなかったので久しぶりに今のバージョンってどうなってるかなと
思ってみてみるとパターンマッチが追加されていた。
はてどんなのかとみてみると
https://docs.python.org/ja/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching
| 1 2 3 4 5 6 7 8 9 10 | def http_error(status):     match status:         case 400:             return "Bad request"         case 404:             return "Not found"         case 418:             return "I'm a teapot"         case _:             return "Something's wrong with the Internet" | 
おなじみのswitch~caseか
どうやら以前から導入を検討されていたようだが結果的には採用にはいたらなかったと。
| 1 2 | case 401 | 403 | 404:     return "Not allowed" | 
上記のようにもかけるのでフォールスルーで書いたりしなくてもこれでいけると。(C#とかフォールスルーをそもそも禁止しているところもあるが)
もし
| 1 | case _: | 
の記載がなかった場合(ほかの言語だとdefault)
| 1 2 3 4 5 6 7 8 | def http_error(status):     match status:         case 400:             return "Bad request"         case 404:             return "Not found"         case 418:             return "I'm a teapot" | 
よくありがちないずれにも該当しないとき、上記の記述だと”None”と返されるようになる。
しっかりとcase _を忘れずに書きましょう。
| 1 2 3 4 5 6 7 8 9 10 11 12 | # point is an (x, y) tuple match point:     case (0, 0):         print("Origin")     case (0, y):         print(f"Y={y}")     case (x, 0):         print(f"X={x}")     case (x, y):         print(f"X={x}, Y={y}")     case _:         raise ValueError("Not a point") | 
タプルも使える。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Point:     x: int     y: int def location(point):     match point:         case Point(x=0, y=0):             print("Origin is the point's location.")         case Point(x=0, y=y):             print(f"Y={y} and the point is on the y-axis.")         case Point(x=x, y=0):             print(f"X={x} and the point is on the x-axis.")         case Point():             print("The point is located somewhere else on the plane.")         case _:             print("Not a point") | 
さらにクラスにも使える。もしpointに数値とかクラスでない場合はcase _に該当すると。
このほかにも辞書のマッチもできるということなので「なんだただのcaseの追加か」と思ってたらだいぶ違っていました。



