Python import error: 'Cannot import name' - python

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?

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"

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.

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

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'

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.

Related

How to import a file in python?

How to access models/usrs from resources/user
├───models
| └───user.py
├───resources
| └───user.py
First I import it like this one:
from code.models.user import UserModel
But I got a compile-time error:
`Cannot find reference 'models' in 'code.py'`
And I tried another way like this one:
from ..models.user import UserModel
But I got a runtime error:
ImportError: attempted relative import beyond top-level package
And I added init.py in both files but still doesn't work.
And also I tried these solutions but they don't fix my issue, please help me
Add the models and resources directories to your $PYTHONPATH or use sys.path:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
Or:
import sys
sys.path.insert(0, "/home/project-name/models")
Or add "__ init__.py" to code directory:
from code.models import user
And finally, I fix my issue:
As #Little Bamboo said: I used sys concept for the import like below:
import sys
sys.path.append("D:\\Projects\\Python\\UdemyProjects\\SixSimplifyingTwo")
from mycode.models.userone import UserModel
But that was not all, some of my files had the same names and I changed the names of the files.
And also I had a folder called code, and from the below link I understood that code is a built-in Python module and I changed the code folder name.
Werkzeug AttributeError: 'module' object has no attribute 'InteractiveInterpreter'

How to dynamically import modules?

I am trying to import modules dynamically in Python. Right now, I have a directory called 'modules' with two files inside; they are mod1.py and mod2.py. They are simple test functions to return time (ie. mod1.what_time('now') returns the current time).
From my main application, I can import as follows :
sys.path.append('/Users/dxg/import_test/modules')
import mod1
Then execute :
mod1.what_time('now')
and it works.
I am not always going to know what modules are available in the dirctory. I wanted to import as follows :
tree = []
tree = os.listdir('modules')
sys.path.append('/Users/dxg/import_test/modules')
for i in tree:
import i
However I get the error :
ImportError: No module named i
What am I missing?
The import instruction does not work with variable contents (as strings) (see extended explanation here), but with file names. If you want to import dynamically, you can use the importlib.import_module method:
import importlib
tree = os.listdir('modules')
...
for i in tree:
importlib.import_module(i)
Note:
You can not import from a directory where the modules are not included under Lib or the current directory like that (adding the directory to the path won't help, see previous link for why). The simplest solution would be to make this directory (modules) a package (just drop an empty __init__.py file there), and call importlib.import_module('..' + i, 'modules.subpkg') or use the __import__ method.
You might also review this question. It discusses a similar situation.
You can achieve something like what you are proposing, but it will involve some un-pythonic code. I do not recommend doing this:
dynamic_imports = dict()
for filename in tree:
name = filename.replace('.py', '')
dynamic_imports[name] = __import__(name)

Importing classes defined in the same module

I am having trouble using my classes that I've defined in a module. I've looked at this stackoverlfow post, and the answer seems to be "you don't need imports." This is definitely not the behavior I'm experiencing. I'm using Python 3.3. Here is my directory structure:
root/
__init__.py
mlp/
__init__.py
mlp.py
layers/
__init__.py
hidden_layer.py
dropout_layer.py
My problem is this: the class defined in dropout_layer.py extends the class in hidden_layer.py, but when I try to import hidden_layer, I sometimes get an error depending on the directory I execute my code from. For instance, from layers.hidden_layer import HiddenLayer then I run my code if I execute it from root/mlp. This import does not work, however, if I execute my code from root. This is strange behavior to me. How can I get this working correctly?
My only non-empty __init__.py file is in root/mlp/layers/:
# root/mlp/layers/__init__.py
__all__ = ['hidden_layer', 'dropout_layer']
In Python 3 you can prepend a . for an import relative to the location of the current module:
from .hidden_layer import HiddenLayer

Python imports from subfolders

I am attempting to grade some python submissions that are in separate folders for each student. To do this, there is a function, say f() which I want to run. I understand that if my current path is the same as the one where the file is located, I can simply do
import filename
filename.f()
However, are there better ways? For instance, let's say the directory structure is as follows:
main.py
student/run_this.py
I know that if there is a "__init__.py" file in the student folder, I can just type
import student.run_this
However, without that file, it doesn't work.
Some similar questions I found were
Import module from subfolder
How to do relative imports in Python?
http://www.daniweb.com/software-development/python/threads/192000/import-from-a-subdirectory-of-a-directory-on-pythonpath
but none of these gave particularly satisfying answers.
create an __init__.py module inside the folder student which should contain
from . import *
You can then call any modules from student folder to its parent folder modules as
import student.module.py
If you post any other errors you are facing, we can help further.

Import custom package in python google app engine

OK guys I can't find a solution anywhere for my problem, and I hope the solution is a simple one. Previously I had a flat file system for my gae project with no folders. I've been refactoring some code and I tried to put some in a folder. I'm a bit new and I've never done something like this before, but nothing on the internet suggests that I shouldn't easily be able to move my files into a folder. I added the __init__.py file to the folder and I import the folder name from my main program. However when I attempt to access a particular function in one of the files, it chokes and says AttributeError: 'module' object has no attribute 'site1_ripper'
here is my file structure:
main.py
SiteCrawlers\
__init__.py
site1_ripper.py
here are important parts of the files:
main.py
import SiteCrawlers
class Updater(webapp.RequestHandler):
def get(self):
SiteCrawlers.site1_ripper.siteCrawler()
site1_ripper.py
def siteCrawler()
#stuff here
I think the problem is that you need to explicitly import site1_ripper unless it's specified in __init__.py. Make your main import be:
import SiteCrawlers.site1_ripper
In your main file try:
from SiteCrawlers.site1_ripper import siteCrawler
class Updater(webapp.RequestHandler):
def get(self):
siteCrawler()

Categories

Resources