Python: 'Private' module in a package

Frederick The Fool picture Frederick The Fool · Aug 30, 2010 · Viewed 22.1k times · Source

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?

Answer

Jeremy picture Jeremy · Feb 15, 2012

I prefix private modules with an underscore to communicate the intent to the user. In your case, this would be mypack._mod_b

This is in the same spirit (but not completely analogous to) the PEP8 recommendation to name C-extension modules with a leading underscore when it’s wrapped by a Python module; i.e., _socket and socket.