0

I have a package with the following structure

package/
│
└───__init__.py
│
└───sub/
    └───__init__.py
    │
    └───XWrap.py # implements class X
    └───YWrap.py # implements class Y

The first __init__.py looks like this:

from . import sub

The second __init__.py looks like this:

from .XWrap import X
from .YWrap import Y

Doing this, the user sees the following

package
│
└───sub
    └───X
    └───XWrap
    └───Y
    └───YWrap

I would like to have a cleaner interface where I don't see YWrap and XWrap. How can I achieve this?

This is the same question asked in a comment here: Python packages - import by class, not file but couldn't find a definite answer.

Georgian Sarghi
  • 373
  • 1
  • 3
  • 9
  • What exactly do you mean by "see" in this case? eg. you don't want it to autocomplete, or you want the import to fail? Perhaps underscore the files or use `__all__`. – Peter Jul 19 '22 at 10:36
  • Above I just used the `dir` function to explore the module structure. So I guess I want the import to fail. If I am not mistaken `__all__` applies to imports of the form `from package import *` right? – Georgian Sarghi Jul 19 '22 at 10:44
  • 1
    I'd say it's likely not very pythonic to attempt to hide things from `dir` and fail imports (if even possible). I'd suggest just call it `_XWrap.py` and `_YWrap.py` if you don't want things to be user facing. – Peter Jul 19 '22 at 10:58
  • I may end up doing that, but it doesn't satisfy me. Most files in my project will need an underscore and I feel there should be a better way. – Georgian Sarghi Jul 19 '22 at 11:23
  • Another suggestion then - have a different folder such as `_sub` for all the private stuff, and import from that into the main `sub`. – Peter Jul 19 '22 at 11:56

0 Answers0