2

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?

Jacs
  • 1,437
  • 4
  • 21
  • 31

5 Answers5

5

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"

Beweeted
  • 319
  • 2
  • 7
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.

Muck
  • 21
  • 2
1

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
lapin
  • 2,098
  • 2
  • 21
  • 30
  • Worked for me! Unsure why though... I'd removed the pycache folder prior to trying this which didn't work – Nihir Dec 11 '20 at 13:36
0
from main wikiSpider directive try:

from _wikiSpider._spiders.items import Article 


orelse from terminal open your _spiders directive and try:

from items import Article

Here we want to open the items.py file where we created Article class, so when you give some wrong directive or file , it cant find the items.py file that you created, so it shows 'Cannot import error'

Nissa
  • 4,636
  • 8
  • 29
  • 37
0

What worked for me is removing the __pycache__ folder. I was moving class files around and changing the directory hierarchy up and the cache must have had old names/locations. Deleting it and running my program again created a new cache and the error was no longer present.

wetjosh
  • 6,288
  • 4
  • 23
  • 32