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.

  • I'm not interested in debating of whether or not it was a good choice, just in knowing the history. – Lyndon White Feb 8 '14 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 '14 at 15:31
up vote 15 down vote accepted

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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