When writing a python module and functions in it, I have some "public" functions that are supposed to be exposed to outsiders, but some other "private" functions that are only supposed to be seen and used locally and internally.
I understand in python there is no absolute private functions. But what is the best, most neat, or most used style to distinguish "public" functions and "private" functions?
I list some of the styles I know:
__all__
in module file to indicate its "public" functions (What's the python __all__ module level variable for?)Is there any other idea or convention that people use?
Thank you very much!
In python programming, there are no private methods that cannot be accessed except inside the class. To define the private method, you have to prefix the member name with a double underscore(__).
Private functions are functions that reside in subdirectories with the special name private.
Function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.
From Python's Class module documentation:
Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With