Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
Importing a module runs its top-level code once and caches it in sys.modules; circular imports fail when a module uses a name from another module that has not finished executing. The __main__ check runs code only when the file is executed directly.
On the first import, Python finds the module on sys.path, executes it from top to bottom and stores it in sys.modules, so later imports reuse the same object. If module a imports b while b imports a, one of them sees a partially initialized module, and from a import X fails with ImportError when X is not yet defined. Fixes include moving shared code into a third module, importing inside a function, importing the module instead of the name, or importing only for type checking under TYPE_CHECKING. Each module's name is 'main' when it is run as a script, so guarding entry code with this check prevents it from running when the module is imported, for example by tests.