Skip to content
Advertisement

Import function from submodule in __init__.py without exposing submodule

I’ working on a Python project with a directory structure similar to this:

foo/
├── bar
│   ├── bar1.py
│   ├── bar2.py
│   └── __init__.py
└── __init__.py

Where the module bar1 defines the function function1.

I would like to have users of my code import function1 (and nothing else) directly from foo, i.e. via from foo import function1. Fair enough, that can be achieved with the following foo/__init__.py:

from .bar.bar1 import function1

__all__ = ['function1']

The problem now is that someone running import foo in e.g. the REPL will still be presented with foo.bar alongside foo.function1 when trying to autocomplete foo.. Is there a way to “hide” the existence of bar from users without changing its name to _bar?

I might be going about this the wrong way alltogether so I’m open to suggestions on how to restructure my code but I would like to avoid renaming modules.

Advertisement

Answer

You can hide it with deleting bar reference in foo/__init__.py:

from .bar.bar1 import function1

__all__ = ['function1']

del bar

Existence of __all__ affects the from <module> import * behavior only

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement