Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute import module in same package

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.

Expected:

I expect possibility 1 to work just fine.

Why do I want to do this:

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.

like image 218
fractalous Avatar asked May 08 '14 08:05

fractalous


1 Answers

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.

like image 86
jfs Avatar answered Sep 21 '22 16:09

jfs