ImportError: Cannot import name X


Question

I have four different files named: main, vector, entity and physics. I will not post all the code, just the imports, because I think that's where the error is. (If you want, I can post more)

Main:

import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the result of movement

Entity:

from vector import Vect
from physics import Physics
class Ent:
    #holds vector information and id
def tick(self, dt):
    #this is where physics changes the velocity and position vectors

Vector:

from math import *
class Vect:
    #holds i, j, k, and does vector math

Physics:

from entity import Ent
class Physics:
    #physics class gets an entity and does physics calculations on it.

I then run from main.py and I get the following error:

Traceback (most recent call last):
File "main.py", line 2, in <module>
    from entity import Ent
File ".../entity.py", line 5, in <module>
    from physics import Physics
File ".../physics.py", line 2, in <module>
    from entity import Ent
ImportError: cannot import name Ent

I am very new to Python but have worked with C++ for a long time. I'm guessing that the error is due to importing entity twice, once in main, and later in physics, but I don't know a workaround. Can anyone help?

1
443
1/3/2019 1:07:10 PM

You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.

431
3/8/2017 2:56:42 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon