Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: Cannot import name X

I have four different files named: main.py, vector.py, entity.py and physics.py. 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.py:

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

entity.py:

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.py:

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

physics.py:

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'm guessing that the error is due to importing entity twice, once in main.py, and later in physics.py, but I don't know a workaround. Can anyone help?

like image 440
jsells Avatar asked Feb 12 '12 20:02

jsells


People also ask

How do you fix ImportError Cannot import name?

Solution 1Check the import class in the python file. If this is not available, create a class in the python file. The python interpreter loads the class from the python file. This will resolve the “ImportError: Can not Import Name” error.

What is python import error?

In Python, ImportError occurs when the Python program tries to import module which does not exist in the private table. This exception can be avoided using exception handling using try and except blocks. We also saw examples of how the ImportError occurs and how it is handled.


2 Answers

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.

like image 81
Teemu Ikonen Avatar answered Sep 22 '22 13:09

Teemu Ikonen


While you should definitely avoid circular dependencies, you can defer imports in python.

for example:

import SomeModule  def someFunction(arg):     from some.dependency import DependentClass 

this ( at least in some instances ) will circumvent the error.

like image 36
bharling Avatar answered Sep 18 '22 13:09

bharling