Search code examples
pythonfunctionimportnested-function

Importing custom created module


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?


Solution

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