Importing custom created module

55 Views Asked by At

So i have created Custom_module.py module that i want to import or rather to import specific function in .py file that i am currently working on.

for example like this:

# Custom_module.py

def test1():
    def test2():
        print("This is test2 function")
    def test3():
        print("This is test3 function")
    
    rest of the test1 func code...

The question is next, is it possible to import only test2() nested function in current .py file?

2

There are 2 best solutions below

0
XMehdi01 On BEST ANSWER

You can return the inner function as a result of calling the outer function. This way, you can access the inner function when you call the outer function.

This is update version Custom_module.py:

# Custom_module.py

def test1():
    def test2():
        print("This is test2 function")    
    def test3():
        print("This is test3 function")
    return test2  

Now, you can import and use test2 in another module as follows:

from Custom_module import test1
test2_function = test1()  
test2_function()
2
XMehdi01 On

Your function test2() in this case and are not accessible from outside the function where they are defined.

If you want to use test2() in another module, you should make it a top-level function by defining it outside of test1().

This is update version Custom_module.py:

# Custom_module.py

def test1():
    print("This is test1 function")

def test2():
    print("This is test2 function")

def test3():
    print("This is test3 function")

Now you can import and use test2() in another python script

Here's an example to illustrate this:

from Custom_module import test2
test2()