Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit to define a function in a function 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) 
like image 345
Aufwind Avatar asked Jul 22 '11 14:07

Aufwind


People also ask

Why do we need to define functions in Python?

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.

What is the purpose of defining functions?

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.

Can you define a function within a function Python?

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.

What happens when you define a function in Python?

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.


2 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?

like image 152
S.Lott Avatar answered Sep 24 '22 00:09

S.Lott


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.

like image 29
John Gaines Jr. Avatar answered Sep 24 '22 00:09

John Gaines Jr.