Search code examples
pythonmodule

Call function from parent module in imported module


I have following problem: I have a .py file with some defined functions and I import a module. From this imported module I want do call a function from the parent module. How do I do this? I searched a lot but didn't found an answer. Here is some test code to show you my problem.

File 1:

from test2 import *

def one():
    print("one")
    pass

def two():
    print("two")
    print("now call function three from test one")

    three()


one()
two()

File 2: Imported as module

def three():
    print("three")
    print("now call function one from test 1")

    one()

Solution

  • You may pass function as parameter:

    Test 1:

    from test2 import *
    
    def one():
        print("one")
        pass
    
    def two():
        print("two")
        print("now call function three from test one")
    
        three(one)  # function one()
    
    
    one()
    two()
    

    Test 2:

    def three(function):
        print("three")
        print("now call function one from test 1")
    
        function()