0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでクロージャを書いてみた

Posted at

概要

決まりきった正規表現は何回もコンパイルする必要がないので、メモ化したいが、グローバル変数は使いたくないので、初めてクロージャを使って実装してみた
まだまだpython初心者なので、あんまりpythonらしいコードが書けてるかは自信がない

実装

import re
from typing import Callable, Pattern


def create_email_regexp_generate_func() -> Callable[[], Pattern]:
    reg = None

    def _email_regexp() -> Pattern:
        # regへの参照を可能にする
        nonlocal reg
        if reg is None:
            reg = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
        return reg

    return _email_regexp

これで、初回呼び出し時のみコンパイル処理が走り、以後はreg変数に保持された正規表現オブジェクトを参照するようにできた

generate_email_regexp = create_email_regexp_generate_func()
generate_email_regexp()
generate_email_regexp()
generate_email_regexp()

参考文献

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?