Absolute import module in the same package

I simplified my import problems to this simple basic option. 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())

The launch python b.pycreates ImportError: No module named mypkgboth in Python 2.7.6 and Python 3.3.5. I also tried to add from __future__ import absolute_importthe same problem in both cases.

Expected:

I expect 1 to work fine.

Why I want to do this:

2 . a ( , ). Python 2 , Python 3+ , . , , 1 , ? , .

. script mypkg, from mypkg import a .

python - , , .

+4
3

from mypkg import a - . Python, , . python -m mypkg.b , mypkg.

, mypkg pythonpath.

+6

:

import sys
import os
this_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.dirname(this_dir))

from mypkg import a
print(a.echo())
0

, , mypkg mypkg. , Python, ( ):

# trying /vagrant/mypkg/mypkg.py

, . , , mypkg.py

import a

but this is only your second opportunity higher in another jacket. Not knowing what you want to achieve, I would choose the first example in the Intra-package Reference text . I would write b.py as such:

from a import echo

print(echo('message'))
0
source

Source: https://habr.com/ru/post/1539716/


All Articles