Note that I searched SO for this error and while there were many similar questions, I didn't find one that addressed this particular issue.
I'm working on a Python module that looks like this:
/com
/company
/foo
/bar
I'm editing a source file within the bar
directory and attempting to import classes that live in the foo
directory. I've tried importing the files the following ways:
from com.company.foo import *
from company.foo import *
from foo import *
import com.company.foo
import company.foo
import foo
Each of these produces a similar error:
ImportError: no module named com.company.foo
I have __init__.py
files in each of the directories, including the directory that contains com
.
Not sure what I'm doing wrong here - thanks in advance for you assistance!
This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.
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.
To get rid of this error “ImportError: No module named”, you just need to create __init__.py in the appropriate directory and everything will work fine.
In Python, ImportError occurs when the Python program tries to import module which does not exist in the private table. This exception can be avoided using exception handling using try and except blocks. We also saw examples of how the ImportError occurs and how it is handled.
The directory containing /com
needs to be on the Python path. There are a number of ways to do this:
At the command line, every time:
user@host:~$ PYTHONPATH=/path/to/whatever python some_file.py
In your shell configuration (.bashrc
, .bash_profile
, etc):
export PYTHONPATH=/path/to/whatever
In Python code (I don't recommend this, as general practice):
import sys
sys.path.append('/path/to/whatever')
As some of the commenters said, usually this is handled either by the container (mod_wsgi
, etc) or by your bootstrap/main script (which might do something like option #3, or might be invoked in an environment set up as in options #1 or #2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With