Circular import from Python

Asked 2 years ago, Updated 2 years ago, 70 views

What happens if two modules import each other?

To generalize, what happens if a circulating import occurs in Python?

python circular-dependency circular-reference

2022-09-22 13:18

1 Answers

There is a good discussion in comp.lang.python regarding the previous question. I think this would be a pretty clear answer.

Importing is pretty simple. All you need to remember is the following:

'import' and 'from xxx importyy' are executable phrases. These are executed when a running program reaches the corresponding line.

If a module does not exist in sys.modules, import creates a new module entry in sys.modules and executes the code for that module. It will not be returned to the module you called until you have completed the execution of this code.

If the module exists in sys.modules, import simply returns the module whether the code execution is complete or not. This is why the circulating import returns a partially empty module.

Finally, the running script runs on a module named __main__ and when you import the script from within the script, it creates a new module that is independent of _main__.

If you are familiar with these, you know all about importing modules.


2022-09-22 13:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.