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でのClosure

Last updated at Posted at 2023-03-31

標記を使う機会がありましたので、残しておきます

使った理由は、Exceのカラム番号を定数にセットする際に、1つ1つ指定するのが辛いのと、
間違えていた場合の精神的ダメージ、工数的ダメージが大変大きかったからです

Qiitaを見るレベルの方だと、細かい説明はいらないと思いますので、コードと使い方のみ残します

closure.py
def base(num: int):
    outer_num = num
    def inc():
        nonlocal outer_num
        outer_num += 1
        return outer_num
    return inc

counter = base(0)
NAME_COL = counter() # return 1
ADDRESS_COL = counter() # return 2

counter = base(10)
TEL_COL = counter() # return 11

ポイントはnonlocalで、1つ上の階層のf_aを指定するところでしょうか
このnonlocalがないと、

`local variable 'f_a' referenced before assignment

で怒られてしまいます

この記事がどなたかのお役に立つと嬉しく思います

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