This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:
- test.py
- config.py
config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:
However, I'm getting the following error:
ModuleNotFoundError: No module named 'config'
I'm aware that the py3 convention is to use absolute imports:
from . import config
However, this leads to the following error:
ImportError: cannot import name 'config'
So I'm at a loss as to what to do here... Any help is greatly appreciated. :)
You can simply add following file to your tests directory, and then python will run it before the tests
This example works on Python 3.6.
I suggest going to
Run -> Edit Configurations
in PyCharm, deleting any entries there, and trying to run the code through PyCharm again.If that doesn't work, check your project interpreter (Settings -> Project Interpreter) and run configuration defaults (Run -> Edit Configurations...).
Declare correct sys.path list before you call module:
TL;DR: you can't do relative imports from the file you execute since
__main__
module is not a part of a package.Absolute imports - import something available on
sys.path
Relative imports - import something relative to the current module, must be a part of a package
If you're running both variants in exactly the same way, one of them should work. Anyway, here is an example that should help you understand what's going on, let's add another
main.py
file with the overall directory structure like this:And let's update test.py to see what's going on:
Let's run test.py first:
Here "test" is the
__main__
module and doesn't know anything about belonging to a package. Howeverimport config
should work, since theryan
folder will be added to sys.path.Let's run main.py instead:
And here test is inside of the "ryan" package and can perform relative imports.
import config
fails since implicit relative imports are not allowed in Python 3.Hope this helped.
P.S.: if you're sticking with Python 3 there is no more need in
__init__.py
files.I figured it out. Very frustrating, especially coming from python2.
You have to add a
.
to the module, regardless of whether or not it is relative or absolute.I created the directory setup as follows.
modx.py
mody.py
main.py
when I execute main, this is what happens
I ran 2to3, and the core output was this
I had to modify mody.py's import statement to fix it
Then I ran main.py again and got the expected output
Lastly, just to clean it up and make it portable between 2 and 3.
You have to append the module’s path to
PYTHONPATH
: