0

I have the following directory structure:

package
├── __init__.py
└── core.py

where the contents of core.py are:

def my_super_cool_func():
    crufty_helper_func()
    pass

def crufty_helper_func():
    pass

and the contents of __init__.py are:

from .core import my_super_cool_func

Now, if I go into the Python REPL, I can import package. Moreover, I can do package.my_super_cool_func() and I can't do package.crufty_helper_func() (as expected). But what I can also do is package.core.crufty_helper_func(), which to me, is undesirable.

Is there any way of excluding modules in a Python package? Ideally, in the setup above, I'd prefer for the core module not to be visible in the package package.

steeps
  • 65
  • 6

1 Answers1

0

do use __all__in __init__.py as

__all__ = ['my_super_cool_func']

then you can use it as from package import my_super_cool_func or

import package

x= package.my_super_cool_func

learn __all__

sahasrara62
  • 10,069
  • 3
  • 29
  • 44
  • So I've introduced the line `__all__ = ['my_super_cool_func']` into `__init__.py`, but `core` is still a visibile module in `package`? – steeps Dec 27 '20 at 13:59
  • 1
    well core is python package and you can access it, i don't know how can we make it unaccesible, try rename it to private module as `_core.py` – sahasrara62 Dec 27 '20 at 14:11
  • You can't *actually* make anything private in Python, you can just suggest (by convention) that it's not intended to be used/imported. – CrazyChucky Dec 27 '20 at 14:57
  • @CrazyChucky yes, there is no concept for private or public in python it is just conventional to use _ for private , as OP require `core` cant be hide and can be accessible, but i suggest this to use in sense that others deveolopers got to know that not to import this module directly – sahasrara62 Dec 27 '20 at 16:05
  • 1
    I was agreeing with you, and clarifying for OP. My apologies, that wasn't very clear. – CrazyChucky Dec 27 '20 at 16:07
  • @CrazyChucky don't be sorry, I also didn't explain enough earlier. – sahasrara62 Dec 27 '20 at 16:36
  • So having read more about `__all__`, does it not only apply when using `from package import *`? – steeps Dec 27 '20 at 21:44
  • @steeps when you use `from package import *` it will import all defined fucntions, class, variable in the file, but if you define `__all__` in the python file then it will import all function/class/variable which are define in the `__all__` only – sahasrara62 Dec 28 '20 at 03:30