I noticed that I made about 5 questions related to relative imports, each of which works with working solutions, but with different situations. The more I read documents, the more I test different cases, the more I get confused and ask if I read words correctly.
From pep 328:
A single leading dot indicates a relative import,
starting with the current package. Two or more leading dots
give a relative import to the parent (s) of the current package,
one level per dot after the first.
I understand that the keyword here is the current package. What is the "current package"? This is a module package, where does the execution begin? (that is: a file with __ name __ == "__ main __").
In any case, here is a simple situation using the notation ..
main /
lib /
__init__.py
myLib.py
plugin /
__init__.py
needLib.py
run.py
run.py import needLib: from plugin import needLib
needLib imports myLib: from ..lib import myLib
What happens through my head: (needLib) goes up the package, goes into lib, grabs myLib
Here is how I do it: python run.py
Result: Attempted relative imports outside the top-level package
But when I changed the import call to from .lib import myLib , it works.
I donβt understand why the latter works, but the designation .. is not. Of course, main not a package, so what about just adding init .py , resulting in
main /
lib /
__init__.py
myLib.py
other /
__init__.py
needLib.py
__init__.py
run.py
But it did not matter; still trying to import beyond the top level package
Have a look at this question: python: forced relative import to search from script file
Notation .. really worked! Now that I think about it, I donβt understand why it works. Execution in this scenario started at two levels, starting from where relative imports take place, and execution in this scenario starts from level 1 up where relative imports take place. Also, where I start execution, the situation is identical.
I both say: "Go up one directory, go into the lib package and grab the module you want."
What is the key difference between this situation and the reference situation? Why .. works there but not here? Do I use use 2.6 for this? Or perhaps how am I doing this? python run.py