Python: 'Private' module in a package

Viewed 29811

I have a package mypack with modules mod_a and mod_b in it. I intend the package itself and mod_a to be imported freely:

import mypack
import mypack.mod_a

However, I'd like to keep mod_b for the exclusive use of mypack. That's because it exists merely to organize the latter's internal code.

My first question is, is it an accepted practice in Python programming to have 'private' modules like this?

If yes, my second question is, what is the best way to convey this intention to the client? Do I prefix the name with an underscore (i.e. _mod_b)? Or would it be a good idea to declare a sub-package private and place all such modules there?

5 Answers

One thing to be aware of in this scenario is indirect imports. If in mypack you

from mypack._mod_b import foo
foo()

Then a user can

from mypack import foo
foo()

and be none the wiser. I recommend importing as

from mypack import _mod_b
_mod_b.foo()

then a user will immediately see a red flag when they try to

from mypack import _mod_b

As for actual directory structure, you could even extend Jeremy's answer into a _package_of_this_kind package, where anything in that can have any 'access modifiers' on it you like - users will know there be dragons

Related