Search code examples
pythonpython-importcircular-dependencycyclic-reference

What happens when using mutual or circular (cyclic) imports?


In Python, what happens when two modules attempt to import each other? More generally, what happens if multiple modules attempt to import in a cycle?


See also What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"? for the common problem that may result, and advice on how to rewrite code to avoid such imports. See Why do circular imports seemingly work further up in the call stack but then raise an ImportError further down? for technical details on why and how the problem occurs.


Solution

  • There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.

    Imports are pretty straightforward really. Just remember the following:

    'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.

    If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.

    If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.

    Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.

    Take that lot together and you shouldn't get any surprises when importing modules.