3

In a module, should I use one, two, or no underscores to denote a helper function the user should not call?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
MarJamRob
  • 3,395
  • 7
  • 22
  • 31
  • Good description of single and double underscores here, http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python – Bi Rico May 02 '13 at 21:47

2 Answers2

9

PEP-8, the Python Style Guide, suggests a single leading underscore.

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.
  • ...
Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
2

Probably a single underscore, but it depends on the situation.

Specifically, the Python Style Guide (PEP 8) says:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

See also this question for some much longer answers: What is the meaning of a single- and a double-underscore before an object name?

Community
  • 1
  • 1
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • What particularly does double underscore do in a module? Anything different from single underscore? – MarJamRob May 02 '13 at 21:49
  • Yes, when it's part of a class - it triggers name mangling. See the docs for a full explanation: http://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references – Peter DeGlopper May 02 '13 at 21:53
  • 1
    Broadly speaking, you use it mostly to prevent subclasses from trivially overriding the method. – Peter DeGlopper May 02 '13 at 21:53