ここ最近はPythonを使うことがほとんどなかったので久しぶりに今のバージョンってどうなってるかなと
思ってみてみるとパターンマッチが追加されていた。
はてどんなのかとみてみると
https://docs.python.org/ja/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching
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か
どうやら以前から導入を検討されていたようだが結果的には採用にはいたらなかったと。
case 401 | 403 | 404:
return "Not allowed"
上記のようにもかけるのでフォールスルーで書いたりしなくてもこれでいけると。(C#とかフォールスルーをそもそも禁止しているところもあるが)
もし
case _:
の記載がなかった場合(ほかの言語だとdefault)
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 _を忘れずに書きましょう。
# 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")
タプルも使える。
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の追加か」と思ってたらだいぶ違っていました。



コメント