Inner functions only exist when the code in the outer function is run, due to the outer function being called. This code, on the outer function then can use the inner function normally, and, it has the option to return a reference to the inner function, or assign it to another data structure (like append it to a list it (the outer function) is modifying).
Therefore, the example you give is no-op - the inner_funciton does nothing, even if the function
is called. It is created, and then destroyed when function
exits after the call to print
.
One of the things that are possible to do with inner funcitons are function factories that can make use of variables - which can be simply passed as arguments to the outer function. Therefore, this works as another way in Python of creating permanent parameters for callables - the other way of doing that is by using classes and instances.
So, for this to work, your function
would have to return the inner_function
in its return statement - and, if, besides working, you want this to make any sense, you'd better have something else inside function that the inner_function would make use of - like a permanent parameter.
Then, on the other module, you import the outer function, and call it - the return value is the parametrized inner function:
main.py:
def multiplier_factory(n):
def inner(m):
return n * m
return inner
test.py:
from main import multiplier_factory
mul_3 = multiplier_factory(3)
print(mul_3(2)) # will print 6