Search code examples
pythonclassinternal

How to make a python class not exposed to the outside?


I'm relatively new to Python.

When I did C/C++ programming, I used the internal classes quite often. For example, in some_file.cc, we may implement a class in the anonymous namespace to prevent it from being used outside. This is useful as a helper class specific to that file.

Then, how we can do a similar thing in Python?


Solution

  • Python code doesn't have any such equivalent for an anonymous namespace, or static linkage for functions. There are a few ways you can get what you're looking for

    1. Prefix with _. Names beginning with an underscore are understood to be for internal use to that python file and are not exported by from * imports. it's as simple as class _MyClass.
    2. Use __all__: If a python file contains a list a list of strings named __all__, the functions and classes named within are understood to be local to that python file and are not exported by from *.
    3. Use local classes/functions. This would be done the same way you've done so with C++ classes.

    None these gets exactly what you want, but privacy and restricting in this way are just not part of the language (much like how there's no private data member equivalent). Pydoc is also well aware of these conventions and will provide informative documentation for the intended-to-be-public functions and classes.