jsells
jsells

Reputation: 7619

What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"?

I have some code spread across multiple files that try to import from each other, as follows:

main.py:

from entity import Ent

entity.py:

from physics import Physics
class Ent:
    ...

physics.py:

from entity import Ent
class Physics:
    ...

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 assume the error is due to importing entity twice - once in main.py and later in physics.py - but how can I work around the problem?


See also What happens when using mutual or circular (cyclic) imports in Python? for a general overview of what is allowed and what causes a problem WRT circular imports. See Why do circular imports seemingly work further up in the call stack but then raise an ImportError further down? for technical details on why and how the problem occurs.

Upvotes: 761

Views: 1185755

Answers (16)

Ankit Patidar
Ankit Patidar

Reputation: 477

This is a circular dependency. we can solve this problem by using import module or class or function where 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() 

Upvotes: 22

sailfish009
sailfish009

Reputation: 2927

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.

Upvotes: 1

Paul
Paul

Reputation: 4168

Try this solution: rename your working python script

You should not name your current python script with the name of some other module you import, since you will get that error.

Example:

  1. you are working in medicaltorch.py
  2. in that script, you have: from medicaltorch import X where medicaltorch is supposed to be a separate installed module

This will fail with the ImportError since 2 things refer to medicaltorch

So, just rename your working python script in 1.

Upvotes: 12

Harry M
Harry M

Reputation: 2088

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.

Upvotes: 47

DuniC
DuniC

Reputation: 340

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!

Upvotes: 17

Nicolas Gervais
Nicolas Gervais

Reputation: 36684

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__'

Upvotes: 8

Tomasz Bartkowiak
Tomasz Bartkowiak

Reputation: 15018

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)

Upvotes: 16

djvg
djvg

Reputation: 14315

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.

Upvotes: 6

Evalds Urtans
Evalds Urtans

Reputation: 6704

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)

Upvotes: 6

Bennett
Bennett

Reputation: 317

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.

Upvotes: 1

Nick Brady
Nick Brady

Reputation: 6592

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 🤦‍♂️

Upvotes: 6

Dunes
Dunes

Reputation: 40833

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.

Upvotes: 139

g10guang
g10guang

Reputation: 5305

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

Upvotes: 29

marengaz
marengaz

Reputation: 1769

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.

Upvotes: 21

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

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.

Upvotes: 616

bharling
bharling

Reputation: 2850

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.

Upvotes: 183

Related Questions