Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cannot import name <class>

Tags:

python

I've been wrestling most of the night trying to solve an import error.

This is a common issue, but no previous question quite answers my issue.

I am using PyDev (an Eclipse plugin), and the library Kivy (a Python library)

I have a file structure set up like this:

<code>
    __init__.py
    main.py
    engine.py
    main_menu_widget.py

"code" is held within the eclipse folder "MyProject" but it's not a package so I didn't include it.

The files look like this:

main.py

# main.py
from code.engine import Engine

class MotionApp(App):
    # Ommited

engine.py

# engine.py
from code.main_menu_widget import MainMenuWidget

class Engine():
    # Ommited

main_menu_widget.py

# main_menu_widget.py
from code.engine import Engine

class MainMenuWidget(Screen):
    pass

The error I recieve, in full detail, is:

 Traceback (most recent call last):
   File "C:\MyProject\code\main.py", line 8, in <module>
     from code.engine import Engine
   File "C:\MyProject\code\engine.py", line 6, in <module>
     from code.main_menu_widget import MainMenuWidget
   File "C:\MyProject\code\main_menu_widget.py", line 3, in <module>
     from code.engine import Engine

Any idea what I did wrong here? I just renamed my entire folder structure because I screwed up this module structure so bad, but I think i'm close to how it should look....

like image 201
MintyAnt Avatar asked Mar 04 '13 03:03

MintyAnt


People also ask

How do you fix ImportError Cannot import name Python?

The Python "ImportError: cannot import name" occurs when we have circular imports (importing members between the same files). To solve the error, move the objects to a third file and import them from a central location in other files, or nest one of the imports in a function.

How do you import a class in Python?

Importing a specific class by using the import command You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.


1 Answers

There seems to be a circular import. from engine.py you are importing main_menu_widget while from main_menu_widgetyou are importing engine.

That is clearly a circular import which is not allowed by python.

like image 59
Gaurav Kumar Avatar answered Nov 10 '22 21:11

Gaurav Kumar