内部関数(inner function)とnonlocal宣言

内部関数(inner function)

Pythonでは、関数内部に関数を定義することが可能です。この関数を内部関数(inner function)と呼びます。

def outer_function():
    """ 外側の関数 """
    print('outer')

    def inner_function():
        """ 内側の関数 """
        print('inner')

    inner_function()

outer_function()

先ほどの関数オブジェクトの考え方を応用すると、関数の戻り値として内部関数を返すことができます。以下のサンプルでは、outer_functionを呼び出すと戻り値にinner_functionを関数オブジェクトとして返しています。

def outer_function():
    """ 外側の関数 """
    print('outer')

    def inner_function():
        """ 内側の関数 """
        print('inner')

    # 内側の関数をオブジェクトとしてreturnする
    f = inner_function
    return f

f = outer_function()
# 受け取った内側の関数を実行する
f() # innerが出力される

最初は違和感があるかもしれませんが、「関数を実行すると戻り値に関数が得られる」という実装は様々なライブラリを利用する際に見られるので知っておいてください。

nonlocal宣言

内側で定義した関数から外側のローカル関数を参照することが可能です。内側の関数で外側のローカル変数を変更したい場合、nonlocal宣言を記述することでできるようになります。global宣言と似ていますね。

def outer_function():
    """ 外側の関数 """

    x = 100
    print(x) # 100が出力される

    def inner_function():
        """ 内側の関数 """
        nonlocal x
        x = 200
        print(x) # 200が出力される
    
    inner_function()
    print(x) # 200が出力される
    
outer_function()

外側の関数の変数が内部関数で変更されたことが確認できます。
n