I've simplified my import problems down to this simple base case. Say I have a Python package:
mypkg/
__init__.py
a.py
b.py
a.py contains:
def echo(msg):
return msg
b.py contains:
from mypkg import a # possibility 1, doesn't work
#import a # possibility 2, works
#from mypkg.a import echo # import also fails
print(a.echo())
Running python b.py
produces ImportError: No module named mypkg
on both Python 2.7.6 and Python 3.3.5. I have also tried adding from __future__ import absolute_import
in both cases, same issue.
I expect possibility 1 to work just fine.
Possibility 2 is less desirable. Hypothetically, the standard library could introduce a package called a
(unlikely in this case, but you get the idea). While Python 2 searches the current package first, Python 3+ includes absolute import changes so that the standard library is checked first.
No matter what my reason, possibility 1 is supposed to work, no? I could swear I've done it thousands of times before.
Note: If you write a script external to mypkg
, from mypkg import a
works without issue.
My question is similar to python - absolute import for module in the same directory, but the author implies that what I have should be working.
from mypkg import a
is the correct form. Don't run scripts from inside the Python package directory, it makes the same module available using multiple names that may lead to bugs. Run python -m mypkg.b
from the directory that contains mypkg
instead.
To be able to run from any directory, mypkg
should be in pythonpath.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With