Python Run Inner Function Within Module

102 Views Asked by At

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()
2

There are 2 best solutions below

1
On BEST ANSWER

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

0
On

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.