Python: Closuresを学ぶ ver. 2

Last Updated on August 1, 2021 by shibatau





Python Closures


Python nonlocal


5 Essential Aspects of Python Closures


II.Nested functionsとclosure




say( )関数の中で、display( )関数が定義(nested function)されています。

display( )関数のprint( )の変数は、display( )関数のスコープの外(nonlocal scope)にあります。Local scopeにない変数をfree variableと呼びます。

display( )関数(nested function)とgreeting変数(free variable)を合わせてclosureと呼びます。

上のスクリプトの末尾の”display( )”を”return display”に変更すると、closureを取得できます。


すなわち、say( )関数の”greeting = ‘Hello'”がなくなっても、”Hello”を返します。

これは、Pythonがスコープを超えた変数(multi-scoped variable)のレファランスに、”Hello”を値とするCellと呼ばれるオブジェクトを与えているからです。








def simple_logger(func):
    def decorated(*args, **kwargs):
        print(f"You're about to call {func}")
        result = func(*args, **kwargs)
        print(f"You just called {func}")
        return result

    return decorated

def hello_world():
    print("Hello, World!")


To be continued.

About shibatau

I was born and grown up in Kyoto. I studied western philosophy at the University and specialized in analytic philosophy, especially Ludwig Wittgenstein at the postgraduate school. I'm interested in new technology, especially machine learning and have been learning R language for two years and began to learn Python last summer. Listening toParamore, Sia, Amazarashi and MIyuki Nakajima. Favorite movies I've recently seen: "FREEHELD". Favorite actors and actresses: Anthony Hopkins, Denzel Washington, Ellen Page, Meryl Streep, Mia Wasikowska and Robert DeNiro. Favorite books: Fyodor Mikhailovich Dostoyevsky, "The Karamazov Brothers", Shinran, "Lamentations of Divergences". Favorite phrase: Salvation by Faith. Twitter: @shibatau

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.