Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The circular imports (<code>A</code> imports <code>B</code>, <code>B</code> imports <code>A</code>) in combination with one of the modules being the main script is the problem.</p> <h2>How Python imports modules</h2> <p>When you ask Python to import a module, it first looks through <code>sys.modules</code> to see if a module by that name is already there. If so, it just uses that module. If there is no module by that name, it makes a new module object, places it in <code>sys.modules</code>, and runs the appropriate Python code in that module.</p> <h2>Main scripts</h2> <p>There's a popular idiom that's used in Python scripts: the ubiquitous</p> <pre><code>if __name__ == '__main__': </code></pre> <p>When Python wants to run the main script, it imports that module <em>with the name <code>__main__</code></em>.</p> <p>That's perfectly fine when your main script just does stuff with other modules, but when other modules want to do things to the main module again, you run into trouble: The script importing the main module again is probably importing it by a normal name (like in this case, <code>A</code>). Unfortunately, the already-loaded module is not named <code>A</code>; it's named <code>__main__</code>.</p> <h2>Solutions</h2> <p>A very simple solution would simply be to remove the other modules' dependencies on the main module. Then you will not encounter this unintuitive behavior. One way you might do this is have the main script just be a stub that calls out to another module's <code>main</code> function or something.</p> <p>A different solution would be to have the main script alter <code>sys.modules</code> manually to put itself under another name. This is a little hacky, but it works:</p> <pre><code>sys.modules['A'] = sys.modules[__name__] </code></pre> <p>Now you know.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload