Folder structure:
foo/
bar.py
__init__.py
test.py
foo/__init__.py
has import bar
I am running test.py
which has import foo
How do I get __init__.py
to import bar.py
?
ModuleNotFoundError: No module named 'foo'
Why does Python not create a new scope for my package and make the root for imports the foo
directory?
Relative paths seem to not work either (I'm receiving a SyntaxError
), although I'm looking for a solution that allows absolute paths.
import .bar
Two unacceptable answers:
I can't use import foo.bar
. I need the foo
package to have its own independent layer/scope so I can move it around anywhere in my computer and import it from anywhere. This means the root could change and import foo.bar
will not always work.
I can't add the foo
folder to my path. Obviously this would clutter the path and name conflicts could easily happen. Commence sense would say that this package's files should be separated from the path of what's using it.
Maybe there's a solution to add this package's directory to the path only for the scope of that package, somewhere in __init__.py
?
Per PEP 328, the import X
syntax is purely for absolute imports; since bar
is not a top-level module here, the only valid import X
syntax is import foo.bar
.
The correct way to import bar
from foo
's __init__.py
is:
from . import bar
Your point about wanting "absolute paths", but also wanting something like import .bar
is impossible; even if import .bar
worked, that's clearly a relative path (in that it only makes sense relative to the module that executes it; .bar
would not make sense if imported outside of the foo
package).
As for "Why does Python not create a new scope for my package and make the root for imports the foo directory?" the simple example is to imagine your sub-module is named math
, not bar
. What does:
import math
mean in this context? If it means your sub-module, how do you get the built-in, top-level math
module? These problems (which I've encountered in Python 2 code when I failed to include from __future__ import absolute_import
) are why PEP 328 and default absolute imports exist; one syntax is always absolute (removing ambiguity), and you can use the relative import syntax to perform relative imports (also without ambiguity) when needed.