Python import error: 'Cannot import name'

23,063

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 :

  1. Rename class name with temporary name
  2. Put the same temporary name in import statement in __init__.py
  3. Now that works, put your old name again
Share:
23,063
Jacs
Author by

Jacs

Updated on April 08, 2020

Comments

  • Jacs
    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
    Nihir over 3 years
    Worked for me! Unsure why though... I'd removed the pycache folder prior to trying this which didn't work