Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a nested function in a different file in python? [duplicate]

I have a file called main.py which contains the following code:

def function(a):
     def inner_function(b):
           return b**2
     print("Reached here!")

Now I have a different file named test.py and I want to import the function inner_function from main.py. Currently I am doing this in my test.py, but it's not working:

from main import function
from function import inner_function

print(inner_function(2))
like image 585
pikachuchameleon Avatar asked Oct 29 '25 02:10

pikachuchameleon


1 Answers

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
like image 105
jsbueno Avatar answered Oct 31 '25 17:10

jsbueno