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)
In Python, a function is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable.
Writing re-usable blocks of code Quite often when carrying out a project, some set of tasks will need to be repeated with different input. To ensure that the analyses are carried out the same way each time, it is important to wrap the code into a named function that is called each time it's needed.
If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With