Search code examples
pythonaccess-modifiers

"Private" (implementation) class in Python


I am coding a small Python module composed of two parts:

  • some functions defining a public interface,
  • an implementation class used by the above functions, but which is not meaningful outside the module.

At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.

So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.


Solution

  • Use a single underscore prefix:

    class _Internal:
        ...
    

    This is the official Python convention for 'internal' symbols; from module import * does not import underscore-prefixed objects.

    Reference to the single-underscore convention in the Python 2 and Python 3 documentation.