10

In python a module private function or variable is named _foo. If it is private to a class it is names __foo, The mechanics behind how these work are different, however that is of little relevance to the question.

Why, during the design of the Python language was the double underscore characters chosen for class private members? Why not single underscore, like for module private? Why not some other character that is more visible? (Differentiating between _ and __ is hard).

I'm sure there is some history here, but I'm having trouble finding it, because all I find are tutorials telling me what it means, rather than why it is that way.

3
  • I'm not interested in debating of whether or not it was a good choice, just in knowing the history. Feb 8, 2014 at 15:29
  • 1
    Single underscores are not for module-private stuff specifically, they're also used for a class's private members. The difference between single and double underscores is only name mangling, which is often unnecessary or even harmful in classes.
    – user7043
    Feb 8, 2014 at 15:31
  • "In python a module private function or variable is named _foo..." this is wrong: see here python.org/dev/peps/pep-0008/#descriptive-naming-styles. In a nutshell underscores are a scraping convention, they do not make anything private (the methods are still accessible from outside).
    – gented
    Jan 25, 2019 at 9:46

1 Answer 1

17

Python Enhancement Proposal (PEP) 8 explains the intended meaning behind single- and double-underscore names, among other conventions. Like many of the early PEPs, it represents Guido van Rossum's preferences, and as Python's acknowledged Benevolent Dictator for Life, his preferences are generally followed by the Python community.

The use of double underscores to indicate "magic" words goes at least as far back as the C preprocessor, which used that convention starting in the 1970s (e.g., __FILE__, __LINE__). It did so because there were no symbols that were off-limits to the preprocessor, so a rarely-used naming pattern (multiple underscores and upper case words) virtually ensured a lack of conflicts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.