I am having a problem with modules and packages. I can make my imports work outside the package or I can make them work inside the package. I have not figured out a way to make them work in both scopes and I assume this is because I am still rather ignorant about Python.
This demonstrates the problem. I have a program that uses a package:
program.py
a.py
File "...\b.py" line 1 in <module>
Module Not Found: No Module named a
I changed module b to use a relative reference:
b.py
This demonstrates the problem. I have a program that uses a package:
program.py
import package.b as b print(b.average(2, 4))Inside the package I have two modules: a and b.
a.py
def sum(x, y): return x + yb.py
import a def average(x, y): return a.sum(x, y) / 2The directory structure is:
Output:program.py
package\
__init__.py <-- Empty
a.py
b.py
If I run b.py there are no errors. When I run program.py I get the messageFile "...\b.py" line 1 in <module>
Module Not Found: No Module named a
I changed module b to use a relative reference:
b.py
from . import a def average(x, y): return a.sum(x, y) / 2If I run program.py there are no errors. When I run b.py I get the message
Error:File "....\b.py" line 1 in <module>
from . import a
ImportError: attempted relative import with no known parent package
I have read dozens of tutorials on how to make a package. I have read dozens of articles about import and __init__.py and PYTHONPATH and setup.py and every topic that looks like it may point toward and answer. I fear I am missing some vital piece Python understanding and this is so trivial that nobody talks about it.