access modifiers – Private (implementation) class in Python

access modifiers – Private (implementation) class in Python

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 short:

  1. You cannot enforce privacy. There are no private classes/methods/functions in Python. At least, not strict privacy as in other languages, such as Java.

  2. You can only indicate/suggest privacy. This follows a convention. The Python convention for marking a class/function/method as private is to preface it with an _ (underscore). For example, def _myfunc() or class _MyClass:. You can also create pseudo-privacy by prefacing the method with two underscores (for example, __foo). You cannot access the method directly, but you can still call it through a special prefix using the classname (for example, _classname__foo). So the best you can do is indicate/suggest privacy, not enforce it.

Python is like Perl in this respect. To paraphrase a famous line about privacy from the Perl book, the philosophy is that you should stay out of the living room because you werent invited, not because it is defended with a shotgun.

For more information:

access modifiers – Private (implementation) class in Python

Define __all__, a list of names that you want to be exported (see documentation).

__all__ = [public_class] # dont add here the implementation_class

Leave a Reply

Your email address will not be published. Required fields are marked *