1

How can I call an inner function within a Python module?

I have created a Python module. Within this module, there is a function. Within this function, there is a nested function. I saved the Python file with the name custom_module.py.

I have then called this module using the statement import custom_module.

I have then tried to call the nested function. I did this using the statement custom_module.outer_function().inner_module().

This has not called the function correctly. How could I call the inner function from within a Python module, or will I need to create separate functions and not use nested functions.

I do not always want to call the inner functions when I run the outer function.

An example of a file named module.py:

def outerFunction():
    print("This is the outer function")
    def innerFunction():
        print("This is the inner function")

An example of the main file:

import module
module.outerFunction().innerFunction()
mufc9000
  • 9
  • 6
  • 1
    Can you give an example of the function definition (inner and outer)? Are you `return`ing the inner function in the outer function? If not, this simply won't be possible, regardless of if it's in a module or not. – Axe319 May 17 '23 at 15:30
  • Per your edit. Once a function is run, all variables in it's body are lost unless they are `return`ed and assigned to something. `innerFunction` is such a variable. You can `return` it with `return innerFunction` and capture it with `my_variable = outerFunction()`, and then call it with `my_variable()`. That is what @Chris 's answer is doing. Or do it in one call with `outerFunction()()`. – Axe319 May 17 '23 at 15:46

2 Answers2

2

Something like the following presumably.

def foo():
  def bar():
    print("foo bar")
  bar()

The function bar in this case is locally scoped to the function foo can cannot be called outside of that scope, unless it is returned from that scope to the outer scope.

>>> def foo():
...   def bar():
...     print("foo bar")
...   bar()
...   return bar
...
>>> bar = foo()
foo bar
>>> bar()
foo bar

It's the same thing you'd see if you wanted to access a variable locally scoped to a function outside of the function's scope.

def foo():
  x = 42
  print(x)

You would not expect to be able to access x except within the scope of the function foo.

Chris
  • 26,361
  • 5
  • 21
  • 42
-2

You could use if statements within the outer function. This will allow you to only run the inner functions which need to be run. For example:

def outerFunction(parameter):
    print("This is the outer function")
    def innerFunction1():
        print("This is the first inner function")
    def innerFunction2():
        print("This is the second inner function")
    if parameter == "firstFunction":
        innerFunction1()
    else if parameter == "secondFunction":
        innerFunction2()

outerFunction(secondFunction)

The output of the above code would be This is the second inner function

mufc9000
  • 9
  • 6