What is the benefit to define a function in a function in python?
Question:
I encountered this piece of python code (pasted below) on effbot and I was wondering:
Why defining a function within a function?
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)
Answers:
Why defining a function within a function?
To keep it isolated. It’s only used in this one place. Why define it more globally when it’s used locally?
It’s just another way of breaking down a large function into smaller pieces without polluting the global namespace with another function name. Quite often the inner function isn’t a stand-alone so doesn’t rightfully belong in the global namespace.
Often the main reason of such code is function closures. It is powerful thing that is applicable not only to Python. E.g. JavaScript gains a lot from them.
Some points about closures in Python – closures-in-python.
I encountered this piece of python code (pasted below) on effbot and I was wondering:
Why defining a function within a function?
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)
Why defining a function within a function?
To keep it isolated. It’s only used in this one place. Why define it more globally when it’s used locally?
It’s just another way of breaking down a large function into smaller pieces without polluting the global namespace with another function name. Quite often the inner function isn’t a stand-alone so doesn’t rightfully belong in the global namespace.
Often the main reason of such code is function closures. It is powerful thing that is applicable not only to Python. E.g. JavaScript gains a lot from them.
Some points about closures in Python – closures-in-python.