LoginSignup
1
2

More than 1 year has passed since last update.

pythonでcase文を書く

Posted at

python3.101 リリースが2022/04くらいなので今更感はあるが、、

主要な変更点

  • 構造的パターンマッチング(case構文)

構造的パターンマッチング

要するにcase構文. SQLとかではifよりこっちがメインだがpythonではdictif ..elifでなんとかなるだろうと言うことで今まで採用して来なかったらしい。

他の言語と同じように書ける.

example1.py
a:int = 2
match a:
    case 1:
        print("this is 1")
    case 3:
        print("this is 3")
    case _:
        print("Other")
# Other

これまではcaseを書きたければ以下のように書く必要があった.

example2.py
# pattern1
if a == 1:
    print("this is 1")
elif a == 3:
    print("this is 3")
else:
    print("Other")

# patern2
cases = {
        1:"this is 1", 
        3:"this is 3"
        }
cases[a] if a in cases.keys() else "Others"

python~3.9でも同じことはできたが、caseの方が可読性が高い、と言うのが導入理由だったらしい。

ちなみにifとの組み合えわせもでき、その場合はcaseが先に評価され、その後でifが評価される。

example3.py
sample = "hello"
match sample:
    case int(x) if sample > 0:
        print("sample is integer and greater than 0")
    case str(x) if sample == "hello":
        print("sample is string and 'hello'")
    case int(x):
        print("sample is integer")
    case str(x):
        print("sample is string")
    case _:
        print("other!")
# sample is string and 'hello'

ここで2番目のcaseで引っ掛かっているので4番目のcaseでは引っかからない. またcaseでデータ型を判定したい場合には
class(x)のように書く。これは自作のクラスでも使用できる
if type(sample) == と同じ。

その他

個人的には条件分の xが違和感ちょっとあった。条件を柔軟に指定できて便利そうなんだけどね。。
また、caseは予約語だけど普通に変数としても使用できてしまうっぽいので注意。

1
2
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
1
2