Python circular importing?

So i'm getting this error

    Traceback (most recent call last):
      File "/Users/alex/dev/runswift/utils/sim2014/", line 3, in <module>
        from world import World
      File "/Users/alex/dev/runswift/utils/sim2014/", line 2, in <module>
        from entities.field import Field
      File "/Users/alex/dev/runswift/utils/sim2014/entities/", line 2, in <module>
        from entities.goal import Goal
      File "/Users/alex/dev/runswift/utils/sim2014/entities/", line 2, in <module>
        from import Post
      File "/Users/alex/dev/runswift/utils/sim2014/entities/", line 4, in <module>
        from physics import PostBody
      File "/Users/alex/dev/runswift/utils/sim2014/", line 21, in <module>
        from import Post
    ImportError: cannot import name Post

and you can see that i use the same import statement further up and it works? Is there some unwritten rule about circular importing? How do i use the same class further down the call stack?

I think the currently accepted answer by jpmc26 comes down too heavily on circular imports. They can work just fine, if you set them up correctly.

The easiest way to do so is to use import my_module syntax, rather than from my_module import some_object. The former will almost always work, even if my_module included imports us back. The latter only works if my_object is already defined in my_module, which in a circular import may not be the case.

To be specific to your case: Try changing entities/ to do import physics and then refer to physics.PostBody rather than just PostBody directly. Similarly, change to do import post and then use post.Post rather than just Post.


Back to homepage or read more recommendations: