Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python circular importing?

So I'm getting this error

Traceback (most recent call last):   File "/Users/alex/dev/runswift/utils/sim2014/simulator.py", line 3, in <module>     from world import World   File "/Users/alex/dev/runswift/utils/sim2014/world.py", line 2, in <module>     from entities.field import Field   File "/Users/alex/dev/runswift/utils/sim2014/entities/field.py", line 2, in <module>     from entities.goal import Goal   File "/Users/alex/dev/runswift/utils/sim2014/entities/goal.py", line 2, in <module>     from entities.post import Post   File "/Users/alex/dev/runswift/utils/sim2014/entities/post.py", line 4, in <module>     from physics import PostBody   File "/Users/alex/dev/runswift/utils/sim2014/physics.py", line 21, in <module>     from entities.post 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?

like image 834
CpILL Avatar asked Mar 05 '14 02:03

CpILL


People also ask

Are circular imports allowed in python?

also just as a reference, it seems circular imports are allowed on python 3.5 (and probably beyond) but not 3.4 (and probably bellow).

How do you avoid circular import errors?

Let's import the functions particularly instead of the whole file. To avoid circular import errors, you can move ```from module import X``` to a place it is needed.

How do I get rid of circular dependency in python?

The easiest way to fix this is to move the path import to the end of the node module. By the way, is there some reason other than you "liking" it that you want one class per module? The few times I've seen this preference, it was because it's Java-like. the link to Importing Python Modules is broken.


1 Answers

I think the answer by jpmc26, while by no means wrong, 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/post.py to do import physics and then refer to physics.PostBody rather than just PostBody directly. Similarly, change physics.py to do import entities.post and then use entities.post.Post rather than just Post.

like image 74
Blckknght Avatar answered Oct 13 '22 00:10

Blckknght