[Tutor] Why define a function inside a function?

Ben Finney ben+python at benfinney.id.au
Fri Jan 29 20:10:51 EST 2016


Ryan Smith <ryan at allwegot.net> writes:

> In trying to understand the logic behind the code for my own
> edification, I was wondering what is the reasoning of defining a
> function in side another function (for lack of a better phrase)?

Sometimes a function is so specific to the workings of another function
that it would not make sense outside that context.

Other times, the information needed to define the function – for
example, a default value for one of the parameters – may be dynamically
determined within the enclosing function. The statement defining the
inner function would not work without that context.

Yet other times, the inner function may be simpler to express by making
use of the enclosing scope of the outer function. Names in the enclosing
function can be referenced in the inner function, without needing to
formally pass them as parameters. Defining the function at the point of
its use keeps the code readable, and keeps the function simpler.

Lastly, functions themselves are objects like any other in Python.
Defining one function inside another, and then using the defined
function object as a value to pass on for further processing, is a
paradigm known as “functional programming” which Python has good support
for. This is how it's done.

-- 
 \        “Like the creators of sitcoms or junk food or package tours, |
  `\         Java's designers were consciously designing a product for |
_o__)                       people not as smart as them.” —Paul Graham |
Ben Finney



More information about the Tutor mailing list