Hi there, I’ve been redirected here by our former BDFL (see Issue 43005: Package Relative Imports - double dot doc example not working - Python tracker) here is my problem :
I’ve been trying to do a double dot import without success, I’ve tried going back to the official documentation in order to figure it out however even the example shown does not work.
Official example : 5. The import system — Python 3.9.1 documentation
The following instructions mimic pretty well the doc example :
mkdir package cd package touch __init__.py mkdir subpackage1 touch subpackage1/__init__.py mkdir subpackage2 touch subpackage2/__init__.py echo "eggs = 42" > subpackage2/moduleZ.py echo "from ..subpackage2.moduleZ import eggs" > subpackage1/moduleX.py python subpackage1/moduleX.py cd subpackage1 python moduleX.py cd .. echo "from subpackage1 import moduleX" > moduleA.py python moduleA.py
However I get 3 times the following error :
from …subpackage2.moduleZ import eggs
ImportError: attempted relative import beyond top-level package
Even though the docs say “In […] subpackage1/moduleX.py […] the following are valid relative imports: […] from …subpackage2.moduleZ import eggs”.
I have no idea how to fix the doc as I would love to do “from …subpackage2.moduleZ import eggs” from “subpackage1/moduleX.py” since that’s the structure I’m trying to set up for a Python project of mine but obviously it does not seem to work.
My system uses Python 3.9 and I’ve used Docker to try this scenario on Python 3.8, 3.5 and even 3.2: it does not work either. I’ve also tried on another machine and asked a friend to try, no luck.
I’m hoping someone here can explain how double dot imports work and help fix the documentation accordingly.