旅行好きなソフトエンジニアの備忘録

プログラミングや技術関連のメモを始めました

【Python】 クロージャ内外で変数を共有する

書籍”Effective Python”項目15のメモです。Pythonを始めて半年経ちますが、真面目に言語自体の勉強をしていなかったので空き時間使ってまだ知らなかった事のメモをします。

Pythonにはnonlocalというキーワードがあり、これによりクロージャ内外でデータを共有できるようです。

def outer_func1():
    found = False
    def inner_func():
        # outer_func1のfoundとは別の変数
        found = True
    inner_func()
    print(found)
# Falseと表示される
outer_func1()

def outer_func2():
    found = False
    def inner_func():
        # 変数foundを外と共有
        nonlocal found
        found = True
    inner_func()
    print(found)
# Trueと表示される
outer_func2()

Effective Python ―Pythonプログラムを改良する59項目

Effective Python ―Pythonプログラムを改良する59項目