Reputation: 159
my_project
-my_project
- __init__.py
- main.py
- constants.py
-test
- __init__.py
- test_main.py
test_main.py from my_project import main
main.py import constants
When I run nosetests in my_project, I end up getting ImportError: No module named 'constants'
Both __init__.py
files are blank.
If I change import constants
to from my_project import constants
in main.py
, nosetests work. However, now if I just run python main.py
I get ImportError: No module named 'my_project'
.
Can someone help me point out what I'm doing wrong? I've searched quite a few posts but I haven't been able to fix it myself. Thanks.
Upvotes: 5
Views: 876
Reputation:
You're attempting a relative import in Python 2 style in a Python 3 project: import constants
will, in Python 3, attempt to import constants
at the main sys.path level.
Instead, use something like
from . import constants
in main.py
See for example PEP 404:
In Python 3, implicit relative imports within packages are no longer available - only absolute imports and explicit relative imports are supported.
and this SO question.
Upvotes: 2
Reputation: 363324
In main.py -> import constants
is an implicit relative import (bad). It should be changed to the more usual from my_project import constants
.
You mentioned this makes nosetests work. Note: you don't need the __init__.py
in the tests sub-directory, and in fact this is usually discouraged.
Now to fix your error with python main.py
having an import error, well that is normal if you haven't included it in your sys.path
. There are various ways around this -
Upvotes: 3