Pythonのパターンマッチ

Python.jpで Python 3.10の新機能(その1) パターンマッチ を紹介したけど、流行るだろうかね?便利っちゃ便利だから、Python3.9がEOLを迎えれば結構使われるんじゃないかと思う。

これはmatch-caseを使ってRustとかのResultっぽい使い方をしてみた例。

class Result:
    _inspected = False
    def __del__(self):
        if not self._inspected:
            print(f"{self} は確認されませんでした")

class Ok(Result):
    __match_args__ = ("value", )

    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        self._inspected = True
        return self._value

class Error(Result):
    __match_args__ = ("reason", )

    def __init__(self, reason):
        self._reason = reason

    @property
    def reason(self):
        self._inspected = True
        return self._reason


def test(result):
    match result:
        case Ok(value):
            print(value)
        case Error(reason):
            print(reason)
        case _:
            print("WTF!")

def to_int(s):
    try:
        return Ok(int(s))
    except Exception as e:
        return Error(str(e))

test(to_int("1234")) # -> 1234
test(to_int("abcdefg")) # -> invalid literal for int() with base 10: 'abcdefg'
Amazon.co.jpアソシエイト: