1

The following is simplified code for better understanding. There are two modules,

The first:

from modulo2 import f1

f = [f1 + 4, f1 + 2]
def first():
    print(f[0])

def second():
     print(f[1])

The second:

from modulo1 import first, second

f1 = 0
def main_function(f1):
    first()
    second()

main_function(5)
main_function(10)
#
#etc

It is a case of circular import, and what I want is that when executing main_function(f1) the variable f1 is modified in the first module according to the given argument.

I have tried many ways without success, I always get an error on import.

ImportError: cannot import name 'first'
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

0

What you have is massive code smell. The best design will have modules that are modular: self-contained in terms of the resources they use. Using global variables prevents effective modularity.

Additionally, when you define a list, the elements are evaluated once. For example, the expression f1 + 4 is only evaluated once, even if you were to successfully define f1 in modulo1.

You can solve both problems by passing your data around and using additional functions to define dynamic behavior.

def f(f1):
    return [f1 + 4, f1 + 2]

def first(f1):
     print(f(f1)[0])

def second(f1):
     print(f(f1)[1])

Notice that modulo1 does not refer to modulo2 at all in this incarnation, but presents the same functionality as before. You can simplify it further:

def first(f1):
     print(f(f1 + 4))

def second(f1):
     print(f(f1 + 2))

Now your imports will work:

from modulo1 import first, second

def main_function (f1):
    first(f1)
    second(f1)

main_function(5)
main_function(10)
#
#etc
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
-1

I found this answer in stackoverflow itself. Based on this, in order to solve your cross import there are few changes that are needed.

first file, lets say modulo1.py

f=[] # creating a empty list

def start():
    from modulo2 import f1 # import the cross module inside a function rather than in the top
    global f # using the global "f", so assigned values will be same through out the program
    f = [f1 + 4, f1 + 2] # adding values to list "f"

def first():
     print (f[0])

def second ():
     print (f[1])

second file, lets say modulo2.py

from modulo1 import start, first, second

f1 = 0
def main_function(f1):
     start() # this is called to create the list "f" in modulo1.py
     first()
     second()

def main():
    main_function(5)
    main_function(10)


if __name__ == "__main__": # this will make sure main_fucntions will only run once as we are doing cross import
    main()
Sai Ram
  • 24
  • 2
  • That looks pretty terrible. Instead of having one difficult to understand piece of code that the interpreter actually complains about, you now have a whole bunch of bad code to obscure the problem – Mad Physicist May 02 '23 at 16:01