First, realize I cannot give you a complete list. If you were to ask "why are screwdrivers useful?", I would would talk about screws and paint can lids but would miss their value in termite inspection. When you ask, "Why are nested functions useful?", I can tell you about scoping, closures, and entry points.
First, nesting can be an alternative to classes. I recently wrote some rendering code that took a file name for specialized mark-up code and returned a bitmap. This naturally lead to functions named grab_markup_from_filename() and render_text_onto_image() and others. The cleanest organization was one entry point named generate_png_from_markup_filename(). The entry point did its job, using nested functions to accomplish its task. There was no need for a class, because there was no object with state. My alternative was to create a module with private methods hiding my helpers, but it would be messier.
def generate_png_from_markup_filename(filename):
def grab_markup_from_filename():
...
... # code that calls grab_markup_from_filename() to make the image
return image
Second, I use nesting for closures. The most common example is for creating decorators. The trick is that I return a reference to an inner function, so that inner function and the outer parameter value are not garbage collected.
def verify_admin(function_to_call):
def call_on_verify_admin(*args, **kwargs):
if is_admin(global.session.user):
return function_to_call(*args, **kwargs)
else:
throw Exception("Not Admin")
return call_on_verify_admin # the return value of verify_admin()
use it this way:
def update_price(item, price):
database.lookup(item).set_field('price', price)
update_price = verify_admin(update_price)
or, more concisely:
@verify_admin
def update_price(item, price):
database.lookup(item).set_field('price', price)
And yes, it should be hard to trace. Remember that "def" is just another statement.
So, here are two places nested classes are helpful. There are more. It is a tool.