The most popular programming languages (such as Java and C/C++) have this kind of syntax to declare private attributes and methods of a class instance:
class MyClass {
private:
int _function() {
// Some code here
}
public:
bool _foo() {
// Some code here
}
}
Python doesn't have (and will probably never have) a syntax like this, so they simply create a conventional name to make developers understand that a method is private and should never be accessed from outside the class.
According to PEP-8:
We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).
According to Python 2 and Python 3 class 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).
Using _ may be useful for a tecnique explained below.
According to Python 3 class documentation:
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.
NOTE: The Python documentation mostly talks about "internal use" referring to classes, but it can be referred to modules too, for example:
# main.py
import myModule
functionThatCanBeImported()
# myModule.py
def functionThatCanBeImported(): pass
def _functionThatShouldNeverBeImported(): pass
If somebody creates a package, they don't have to put private functions in the documentation, since they are for internal scope and explainations about them could be useful only to developers.