-1

I have a function in Python

def outer_function():
    def inner_funtion():
        print ('inner message')
    print('outer message')
    sys.exit()

How do I call the inner function? I'm quite new to the inspect library and with closure if this qualifies as closure.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Dart Feld
  • 21
  • 4

3 Answers3

0

You call it as any other function inner_funtion() but it's accessible only in outer_function scope obviously.

Jozef Cipa
  • 2,133
  • 3
  • 15
  • 29
0

You can use inner_function() anywhere in the scope where inner_function() is defined, that is anywhere in outer_function() after you defined inner_function().

galfisher
  • 1,122
  • 1
  • 13
  • 24
0

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.

Daniel R. Livingston
  • 1,227
  • 14
  • 36