I have a package foo_package
organized like this:
foo/
setup.py
README.md
...
foo_package/
__init__.py
bar.py
baz.py
The module bar.py
defines one 'public' function also named bar
, and both the module and the function benefit hugely from being named exactly bar
. bar.py
also defines some 'private' helper functions.
Inside of __init__.py
I make a top-level import of bar.bar
so that foo_package.bar
will be the API of the overall package.
# __init__.py:
from .bar import bar
But now I am getting bitten by relative imports.
First, if I am debugging or working in an interactive prompt like IPython, naively pasting from .bar import bar
doesn't work. I can get around this by launching IPython inside foo_package
and using from foo_package import bar
instead.
But then how can I import the bar
module and not the exported bar
function? E.g. variants of
from foo_package import bar
import foo_package.bar as bar
etc., all import the function bar
, meanwhile any time that bar.py
also contains a relative import to another module, such as
# inside bar.py
from .baz import helper_function
then the plain
import bar
won't work either.
The package-level 'ghosting' of bar
the module with bar
the function is the correct behavior. How can I maintain this while also being able to import bar
the module in local development (especially in an interactive environment like IPython)?
If you really do have a compelling reason to keep the shadowing, you can access the module object through
sys.modules
:There's also
importlib.import_module
: