python – beyond top level package error in relative import
python – beyond top level package error in relative import
EDIT: There are better/more coherent answers to this question in other questions:
Why doesnt it work? Its because python doesnt 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 doesnt have any more (i.e. sibling directories of a loaded location). Its 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 whats in package
and youre just accessing a child directory of a loaded location.
Why doesnt python consider the current working directory to be a package? NO CLUE, but gosh it would be useful.
import sys
sys.path.append(..) # Adds higher directory to python modules path.
Try this.
Worked for me.
python – beyond top level package error in relative import
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.