beyond top level package error in relative import
EDIT: There are better/more coherent answers to this question in other questions:
Why doesn't it work? It's because python doesn't record where a package was loaded from. So when you do python -m test_A.test
, it basically just discards the knowledge that test_A.test
is actually stored in package
(i.e. package
is not considered a package). Attempting from ..A import foo
is trying to access information it doesn't have any more (i.e. sibling directories of a loaded location). It's conceptually similar to allowing from ..os import path
in a file in math
. This would be bad because you want the packages to be distinct. If they need to use something from another package, then they should refer to them globally with from os import path
and let python work out where that is with $PATH
and $PYTHONPATH
.
When you use python -m package.test_A.test
, then using from ..A import foo
resolves just fine because it kept track of what's in package
and you're just accessing a child directory of a loaded location.
Why doesn't python consider the current working directory to be a package? NO CLUE, but gosh it would be useful.
Assumption:
If you are in the package
directory, A
and test_A
are separate packages.
Conclusion:..A
imports are only allowed within a package.
Further notes:
Making the relative imports only available within packages is useful if you want to force that packages can be placed on any path located on sys.path
.
EDIT:
Am I the only one who thinks that this is insane!? Why in the world is the current working directory not considered to be a package? – Multihunter
The current working directory is usually located in sys.path. So, all files there are importable. This is behavior since Python 2 when packages did not yet exist. Making the running directory a package would allow imports of modules as "import .A" and as "import A" which then would be two different modules. Maybe this is an inconsistency to consider.