Absolute import module in same package

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.


Yes it will not work, because at the moment you call print(mypkg.a.echo()), mypkg is still loading (mypkg.__init__ -> mypkg.b). This is because Python loads parent modules first. https://docs.python.org/3/reference/import.html#searching

What you can do is wrap print(mypkg.a.echo()) into a function:

def echo():
   mypkg.a.echo()

And then:

import mypkg.b
mypkg.b.echo()

Or even:

print(sys.modules['mypkg.a'].echo())

Also you can help Python to find your module:

import importlib
mypkg.a = importlib.import_module('mypkg.a')
mypkg.a.echo()