I was playing the the Python's import system in order to understand better how it works, and I encountered another problem. I have the following structure
pkg/
__init__.py
c.py
d.py
subpkg/
__init__.py
a.py
b.py
Inside a.py
I have the following code:
from . import b
from .. import d
And inside c.py
I have the following:
import subpkg.a
Now I receive the following error:
ValueError: attempted relative import beyond top-level package
But why? How can I solve it? I am running c.py
from the IDLE, and pkg
should be considered a package, since it has the __init__.py
file.
The first import works fine, but it's the following that doesn't work:
from .. import d
Because I am attempting to import something from a parent package, but apparently I cannot, for some weird reason.
Python 3 changed the import system so every time you want a module that is around the one you are working, you need relative imports (unless you mess with
PYTHON_PATH
orsys.path
).The correct usage here should be
When you are working with IDLE, you have a totally different environment. Therefore, you could add the current location to your path so imports work again.
try:
It might be weird, but it is for a greater good
PS: If this last thing do not work -- I don't have an IDLE environment right now -- it is probably because the work directory is set wrong.
Try this answer instead: https://stackoverflow.com/a/17361545/754991