Python circular importing?

后端 未结 7 1016
不知归路
不知归路 2020-11-22 05:46

So i\'m getting this error

Traceback (most recent call last):
  File \"/Users/alex/dev/runswift/utils/sim2014/simulator.py\", line 3, in 
    f         


        
7条回答
  •  伪装坚强ぢ
    2020-11-22 06:16

    When you import a module (or a member of it) for the first time, the code inside the module is executed sequentially like any other code; e.g., it is not treated any differently that the body of a function. An import is just a command like any other (assignment, a function call, def, class). Assuming your imports occur at the top of the script, then here's what's happening:

    • When you try to import World from world, the world script gets executed.
    • The world script imports Field, which causes the entities.field script to get executed.
    • This process continues until you reach the entities.post script because you tried to import Post
    • The entities.post script causes physics module to be executed because it tries to import PostBody
    • Finally, physics tries to import Post from entities.post
    • I'm not sure whether the entities.post module exists in memory yet, but it really doesn't matter. Either the module is not in memory, or the module doesn't yet have a Post member because it hasn't finished executing to define Post
    • Either way, an error occurs because Post is not there to be imported

    So no, it's not "working further up in the call stack". This is a stack trace of where the error occurred, which means it errored out trying to import Post in that class. You shouldn't use circular imports. At best, it has negligible benefit (typically, no benefit), and it causes problems like this. It burdens any developer maintaining it, forcing them to walk on egg shells to avoid breaking it. Refactor your module organization.

提交回复
热议问题