Allowing imported python functions to call other imported python functions

Viewed 112

This is my first time ever importing my own scripts and I have some questions as to how imported functions can interact other with other imported functions. This is what my script currently looks like:

from file1 import function1
from file2 import function2

function1()

function 1 looks something like this:

def function1():
    option = input('Option: ')
    if option == 'function 2':
        function2()

and function 2 looks something list this:

def function2():
    option = input('Option: ')
    if option = 'function 1':
        function1()

Whenever I run this it gives me the error that function2 is not defined. I have tried importing the two scripts within each other but this results in a circular import. My primary purpose for doing this is just to keep the functions of one script better organized, so I am wondering if there is a way to accomplish having two imported functions refer to each other or if I should just forget about it.

1 Answers

If function1 invokes function2, function2 must be imported in file1.py.

Your project layout should be organized as follows:

file1.py

from file2 import function2

def function1():
    # function 1 logic
    if condition: 
        function2()

file2.py

def function2():
    # function2 logic

main.py

from file1 import function1

function1()
Related