Afam Rk
Afam Rk

Reputation: 19

why i get circular import error in only one way?

#app.py

print('ran')
from model import func2
print('Imported')
def func1():
    pass
print('func defined')
func2()

#model.py

def func2():
    pass
from app import func1
func1()

output

python app.py

ran
ran
Imported
func defined
Imported
func defined

python model.py

ran
Traceback (most recent call last):
  File "C:/Users/AFAM RK/PycharmProjects/deepdive/test/model.py", line 3, in <module>
    from app import func1
  File "C:\Users\AFAM RK\PycharmProjects\deepdive\test\app.py", line 2, in <module>
    from model import func2
  File "C:\Users\AFAM RK\PycharmProjects\deepdive\test\model.py", line 3, in <module>
    from app import func1
ImportError: cannot import name 'func1' from partially initialized module 'app' (most likely due to a circular import) (C:\Users\AFAM RK\PycharmProjects\deepdive\test\app.py)

app.py run without any error, but while running model.py i get circular import error.

why its happening?

why its not raise error while running app.py?

Upvotes: 0

Views: 48

Answers (1)

tobmei05
tobmei05

Reputation: 461

If you run python app.py the interpeter

  • prints ran (line 1)
  • on line 2 it sees the import statement and starts reading model.py
  • in model.py it sees first the definition of func2 and saves its information for later usage.
  • on the third line of model.py it sees the import statement and jumps back to app.py
  • there it prints ran once more
  • on the second line it sees (again) the import statement but remembers that this was already imported (python imports a module only once).
  • now it executes the rest of app.py and therefore printing imported and func defined (still as part of the import that happened in model.py (print a string at the very end of model.py and you see that this string is printed after func defined)
  • now the import of model.py is over and it continues running the remaining code of app.py resulting in printing imported and func defined again.

Now if you run python model.py the interpreter

  • first sees the definition of func2 and saves its information for later usage
  • on the third line it sees the import statement and jumps to app.py
  • there first ran is printed
  • on the second line it sees the import statement and jumps back to model.py
  • there again (after redefining func2) on the third line remembers, that this import was already done and jumps to line 4 but does not find func1. Now the error is reported.

Upvotes: 1

Related Questions