Should I use underscore before function name in single-file simple python script?
For example, in this script should I add underscore before definition of f and g? This script won't be imported from other files.
def f(x): # or _f(x)?
return x * 2
def g(x): # or _g(x)?
return x ** 2
def main():
x = f(100)
print(g(x))
if __name__ == "__main__":
main()
I read many documents about usage of underscores in python. Many of them says underscores are about OOP-style programming and how import statement works. However, in simple one-file script, I can't find good answer.
What is better pattern?
CodePudding user response:
_ is used to let developers know that the variables and methods are private and should not be modified externally. So use _ if you want to keep the functionality within the class.
NOTE: using _ will not restrict the use of these methods or variables though, it's just a way of representation.
CodePudding user response:
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.
