Reputation: 475
I believe the problem is running the code not importing, as IntelliCode recognizes the module and functions
So here is the structure of my files
-a.py
-tests/
-__init__.py
-b.py
-pages/
-__init__.py
-c.py
Here is c.py
from tests import b
def hello_from_c():
print('C says hi')
Here is b.py
import pages.c as c
c.hello_from_c()
When I run 'python a.py' in terminal with either b or c imported it runs fine. However, when I run either c or b in terminal as a script, trying to import the other file, I get 'no module named tests' or 'no module named pages'. Even though IntelliCode is showing no errors.
What's the reason this is happening?
(Update)
running python -m [packagename].[filename(no .py)]
works
Upvotes: 1
Views: 1134
Reputation: 91
When you run python a.py
, python searches for modules relative to the address a.py
is in, which in your example is the root address. That is why you can import b.py
and c.py
using tests.b
and pages.c
, no matter which file the import code is in (be it a.py
, b.py
, or c.py
).
However, when you run b.py
or c.py
, python's module search scope is relative to the address those files are in. Therefore, when you run b.py
, it looks for a pages
folder inside the tests
folder, which obviously does not exists.
Even if you try using ..
, you will receive a ValueError: Attempted relative import in non-package
. If you really want to import something from another python file in a sibling directory, I suggest you read this thread:
How to fix "Attempted relative import in non-package" even with __init__.py
Upvotes: 5