616

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?

Neuron
  • 3,776
  • 3
  • 24
  • 44
jsells
  • 6,169
  • 3
  • 12
  • 3
  • What's the directory structure of where they are stored and in which directories? – Ben Feb 12 '12 at 20:56
  • 1
    have a look at this answer for loop-importing in python: http://stackoverflow.com/questions/7199466/how-to-break-import-loop-in-python – Gregor Feb 12 '12 at 20:56
  • In general, it's not good coding practice to do `from import `, or `from import *`. Better to import under the module namespace to prevent the chance of overwriting identically named references. – Joel Cornett Feb 12 '12 at 20:57
  • They are all in the same directory named "code", so no real structure. – jsells Feb 12 '12 at 20:59
  • So what Joel is saying, I should probably use 'import vector' and use 'x = vector.Vect(0,0,0)'? And perhaps this will clear it up? – jsells Feb 12 '12 at 21:02
  • @Ben if the module is in a subdirectory, is there a simple answer? Importing works fine from the directory containing the module, but not from the parent directory. There is an \_\_init\_\_.py that works until it cannot import name _foo. For the record, _foo is in C. – yoel Feb 19 '13 at 23:51
  • 1
    @jsells You should just call your classes `Entity` and `Vector` instead of `Ent` and `Vect`, there's no reason to shorten such names. And yes, use `import vector` and then `x = vector.Vector(0,0,0)`. –  Apr 18 '13 at 17:00
  • 7
    Hey @Kevin since you know Java better, what is your impression of this [2008 article](http://interactiveasp.net/blogs/natesstuff/archive/2008/06/09/avoiding-circular-dependencies.aspx) where the author's first sentence refers to how circular dependencies are _"pretty common practice"_ in Java ? – HeyWatchThis May 08 '14 at 20:52
  • Every major language supports circular imports without a problem... C#, C, C++, Java, Objective-C... This isn't 1991. – Kevin Parker May 15 '14 at 13:20
  • I answered a very similar question here: https://stackoverflow.com/questions/50312470/importerror-cannot-import-name-mainclass/50312647#50312647 – Aiden Blishen Cuneo May 13 '18 at 04:13
  • If you can't get away from circular dependencies, you can import directly in the function or class where you need the particular dependency instead of global to the file – Seraf Feb 07 '19 at 18:24

16 Answers16

560

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.

Arkady
  • 12,047
  • 6
  • 36
  • 46
Teemu Ikonen
  • 11,169
  • 4
  • 20
  • 35
  • 2
    Ok, I understand that physics is importing entity which in turn imports physics. But, I can't remove the dependency to physics in entity, because class Ent needs to call it to update its position. I also try to import physics at the end of the file or in the constructor, and that only gives me the NameError: name 'x' is not defined. – jsells Feb 12 '12 at 21:13
  • 5
    There is not much you can do than to refactor your code. If you do not refer Physics in Ent constructor definition move mport just under the Ent. If you do, add method like setPhysics to enable import after constructor. – Teemu Ikonen Feb 13 '12 at 07:22
  • 12
    @jsells Since you have worked with C++ "for a long time", you should know that two classes should NEVER be dependant on each other. This is extremely important in C++, and even if it's not the #1 thing in Python, it's still a really good idea to follow this rule. Never have two classes which know each other, ever. If you need help with creating the structure for your classes, post rest of the code too. How exactly (in terms of code) are `Entity` and `Physics` linked to each other? I'm sure there's a workaround for what you're trying to do. –  Apr 18 '13 at 17:03
  • 9
    @user2032433 That really depends on what you mean by 'know each other'. It is true that good design usually produces a tree of one-way dependencies and this is normally the best approach. But there are exceptions to this. C++ classes certainly can refer to one another circularly. (Although it is impossible for them to be composed of one another.) Without forward-declaration, this is a problem in Python which doesn't always have a C++ solution. – John McFarlane Jun 03 '14 at 19:14
  • 119
    The statement "two classes should NEVER be dependant on each other" is rubbish. Two way (bidirectional ) navigation is very common in object orientation. http://books.google.co.uk/books?id=nHZslSr1gJAC&lpg=PR17&ots=V82ZJRMA1F&dq=OO%20uml%20bidirectional%20navigation&lr&pg=PA42#v=onepage&q=bidirectional&f=false – Martin Spamer Dec 17 '14 at 17:38
  • @MartinSpamer Your link implied one should be the master and the other the slave. Also, it is talking about attributes and not inheritance, you can achieve his example because Python uses duck typing. – Harrichael Jul 27 '17 at 15:10
  • 1
    @MartinSpamer It's common because people are bad at code. http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/ – MirroredFate Sep 10 '17 at 23:53
  • 5
    The State design pattern (for example) is usually implemented with a Context class and a State interface. Instances of State are passed the Context instance so that they can call setState. This requires State to know about Context and vice-versa. How is this classical construct being "bad at code"? Actually that's exactly the problem I'm wrestling with in Python, but didn't have to when I implemented State in Java. – Auspice Dec 01 '17 at 20:17
  • Notice that if you import a module like `import a.b.c`, (where you need c), but in a.b there is an import referencing this file doing the import, it will **still** be a cyclic import. – DarthCadeus Dec 26 '18 at 11:46
  • Thanks!! it helped me to see that I was having a circular dependencies – Alon Samuel Dec 23 '19 at 14:54
158

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.

bharling
  • 2,548
  • 1
  • 14
  • 23
125

This is a circular dependency. It can be solved without any structural modifications to the code. The problem occurs because in vector you demand that entity be made available for use immediately, and vice versa. The reason for this problem is that you asking to access the contents of the module before it is ready -- by using from x import y. This is essentially the same as

import x
y = x.y
del x

Python is able to detect circular dependencies and prevent the infinite loop of imports. Essentially all that happens is that an empty placeholder is created for the module (ie. it has no content). Once the circularly dependent modules are compiled it updates the imported module. This is works something like this.

a = module() # import a

# rest of module

a.update_contents(real_a)

For python to be able to work with circular dependencies you must use import x style only.

import x
class cls:
    def __init__(self):
        self.y = x.y

Since you are no longer referring to the contents of the module at the top level, python can compile the module without actually having to access the contents of the circular dependency. By top level I mean lines that will be executed during compilation as opposed to the contents of functions (eg. y = x.y). Static or class variables accessing the module contents will also cause problems.

Dunes
  • 32,114
  • 7
  • 68
  • 83
25

To make logic clear is very important. This problem appear, because the reference become a dead loop.

If you don't want to change the logic, you can put the some import statement which caused ImportError to the other position of file, for example the end.

a.py

from test.b import b2

def a1():
    print('a1')
    b2()

b.py

from test.a import a1

def b1():
    print('b1')
    a1()

def b2():
    print('b2')

if __name__ == '__main__':
    b1()

You will get Import Error: ImportError: cannot import name 'a1'

But if we change the position of from test.b import b2 in A like below:

a.py

def a1():
    print('a1')
    b2()

from test.b import b2

And the we can get what we want:

b1
a1
b2
g10guang
  • 2,835
  • 1
  • 21
  • 19
20

This is a circular dependency. we can solve this problem by using import module or class or function where we needed. if we use this approach, we can fix circular dependency

A.py

from B import b2
def a1():
    print('a1')
    b2()

B.py

def b1():
   from A import a1
   print('b1')
   a1()

def b2():
   print('b2')
if __name__ == '__main__':
   b1() 
a.patidar
  • 361
  • 2
  • 4
18

I just got this error too, for a different reason...

from my_sub_module import my_function

The main script had Windows line endings. my_sub_module had UNIX line endings. Changing them to be the same fixed the problem. They also need to have the same character encoding.

marengaz
  • 1,287
  • 15
  • 26
18

In my case, I was working in a Jupyter notebook and this was happening due the import already being cached from when I had defined the class/function inside my working file.

I restarted my Jupyter kernel and the error disappeared.

Harry M
  • 1,390
  • 3
  • 14
  • 29
14

As already mentioned, this is caused by a circular dependency. What has not been mentioned is that when you're using Python typing module and you import a class only to be used to annotate Types, you can use Forward references:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

and remove the dependency (the import), e.g. instead of

from my_module import Tree

def func(arg: Tree):
    # code

do:

def func(arg: 'Tree'):
    # code

(note the removed import statement)

Tomasz Bartkowiak
  • 5,269
  • 1
  • 38
  • 44
14

The problem is clear: circular dependency between names in entity and physics modules.

Regardless of importing the whole module or just a class, the names must be loaded .

Watch this example:

# a.py
import b
def foo():
  pass
b.bar()
# b.py
import a
def bar():
  pass
a.foo()

This will be compiled into:

# a.py
# import b
# b.py
# import a # ignored, already importing
def bar():
  pass
a.foo()
# name a.foo is not defined!!!
# import b done!
def foo():
  pass
b.bar()
# done!

With one slight change we can solve this:

# a.py
def foo():
  pass
import b
b.bar()
# b.py
def bar():
  pass
import a
a.foo()

This will be compiled into:

# a.py
def foo():
  pass
# import b
# b.py
def bar():
  pass
# import a # ignored, already importing
a.foo()
# import b done!
b.bar()
# done!
DuniC
  • 193
  • 1
  • 6
9

Don't name your current python script with the name of some other module you import

Solution: rename your working python script

Example:

  1. you are working in medicaltorch.py
  2. in that script, you have: from medicaltorch import datasets as mt_datasets where medicaltorch is supposed to be an installed module

This will fail with the ImportError. Just rename your working python script in 1.

Paul
  • 2,853
  • 22
  • 27
  • 1
    Thanks, this solves the problem that I had. I used colorama library and named file colorama.py, so python didn't know what to import. Changing file name helps. – Marek Bodziony Mar 04 '20 at 21:33
7

If you are importing file1.py from file2.py and used this:

if __name__ == '__main__':
    # etc

Variables below that in file1.py cannot be imported to file2.py because __name__ does not equal __main__!

If you want to import something from file1.py to file2.py, you need to use this in file1.py:

if __name__ == 'file1':
    # etc

In case of doubt, make an assert statement to determine if __name__=='__main__'

Nicolas Gervais
  • 21,923
  • 10
  • 61
  • 96
6

One way to track import error is step by step trying to run python on each of imported files to track down bad one.

  1. you get something like:

    python ./main.py
    

    ImportError: cannot import name A

  2. then you launch:

    python ./modules/a.py
    

    ImportError: cannot import name B

  3. then you launch:

    python ./modules/b.py
    

    ImportError: cannot import name C (some NON-Existing module or some other error)

Tom
  • 14,120
  • 16
  • 41
  • 47
Evalds Urtans
  • 5,160
  • 1
  • 36
  • 26
5

Don't see this one here yet - this is incredibly stupid, but make sure you're importing the correct variable/function.

I was getting this error

ImportError: cannot import name IMPLICIT_WAIT

because my variable was actually IMPLICIT_TIMEOUT.

when I changed my import to use the correct name, I no longer got the error ‍♂️

Nick Brady
  • 4,708
  • 1
  • 30
  • 57
  • 1
    I was ready to kill someone trying to figure out why `from PIL import Pillow` wasn't working. – aalaap Feb 06 '19 at 12:54
5

Also not directly relevant to the OP, but failing to restart a PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...

The confusing part is that PyCharm will autocomplete the import in the console, but the import then fails.

djvg
  • 5,523
  • 3
  • 36
  • 64
1

Not specifically for this asker, but this same error will show if the class name in your import doesn't match the definition in the file you're importing from.

Bennett
  • 317
  • 2
  • 6
  • 16
0

In my case, simply missed filename:

from A.B.C import func_a (x)

from A.B.C.D import func_a (O)

where D is file.

sailfish009
  • 1,790
  • 1
  • 17
  • 26