Python import error: 'Cannot import name'
Solution 1
Like others, I didn't have a circular reference problem. I'd like to generalize the solution here just a bit more though.
Any file name conflict can cause this. You could have multiple sub files with the same name (as above).
Or it could be the file you're working in.
Eg: trello.py as a pet project. from trello import TrelloApi
Import reference will import itself before importing the pip installed package. Attempts to import trello and reference objects directly will fail with "NameError: name '' is not defined"
Solution 2
You have an items.py in both your root and _spiders folder. To reference a file in a subfolder you need the folder name and the file.
from _spiders.items import Article
assuming the file that imports this code is in your root directory. Python uses a you are here, to current file location, for it's directory hierarchy.
Solution 3
Best solution :
- Rename class name with temporary name
- Put the same temporary name in import statement in
__init__.py
- Now that works, put your old name again
Jacs
Updated on April 08, 2020Comments
-
Jacs about 4 years
Im having trouble importing a class on a python module.
Here are my directory structure:
_wikiSpider +scrapy.cfg _wikiSpider +__init__.py +items.py +items.pyc +settings.py +settings.pyc +pipelines.py _spiders +__init__.py +__init__.pyc +articleSpider.py +articleSpider.pyc +items.py
Code breaks at this line:
from wikiSpider.items import Article
Im not sure why, since class Article is defined at items.py (deepest folder)
Can someone give me an explanation?
-
Nihir over 3 yearsWorked for me! Unsure why though... I'd removed the pycache folder prior to trying this which didn't work