Python で関数内に関数を定義する利点は何ですか? 質問する

Python で関数内に関数を定義する利点は何ですか? 質問する

私は以下のPythonコードに遭遇しました(以下に貼り付けます)。エフボットそして私は疑問に思いました:

なぜ関数内で関数を定義するのでしょうか?

import re, htmlentitydefs

##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("(?s)<[^>]*>|&#?\w+;", fixup, text)

ベストアンサー1

なぜ関数内で関数を定義するのでしょうか?

隔離しておくためです。この 1 つの場所でのみ使用されます。ローカルで使用されるのに、なぜグローバルに定義する必要があるのでしょうか。

おすすめ記事