I find myself using this technique quite a bit.
As one of the commenters wrote, you just call it:
def outer_function():
def inner_funtion():
print ('inner message')
print('outer message')
inner_function()
sys.exit()
>>> outer_function()
outer message
inner message
This only works within the scope of outer_function()
, and will return an error if you try to call inner_function()
anywhere but inside outer_function()
.
Using nested functions are a great technique to clean up otherwise unwieldy top-level functions.
As for your second question, the top answer here does a better job than I ever could.