[Tutor] Single Underscore
jfouhy at paradise.net.nz
Mon Jul 11 05:43:14 CEST 2005
Quoting Kevin Reeder <reederk at comcast.net>:
> What's the significance of naming a variable with a single
> underscore as its first character? For example, I'm looking at
> find.py in the standard library and it has variables named _debug
> and _prune.
Basically, it means "These variables are internal and not part of the API;
please do not use them in your code because they may change without warning".
The reference here is PEP-8, the Python style guide:
In addition, the following special forms using leading or trailing
underscores are recognized (these can generally be combined with any
- _single_leading_underscore: weak "internal use" indicator
(e.g. "from M import *" does not import objects whose name
starts with an underscore).
- single_trailing_underscore_: used by convention to avoid
conflicts with Python keyword, e.g.
- __double_leading_underscore: class-private names as of Python 1.4.
- __double_leading_and_trailing_underscore__: "magic" objects or
attributes that live in user-controlled namespaces,
e.g. __init__, __import__ or __file__. Sometimes these are
defined by the user to trigger certain magic behavior
(e.g. operator overloading); sometimes these are inserted by the
infrastructure for its own use or for debugging purposes. Since
the infrastructure (loosely defined as the Python interpreter
and the standard library) may decide to grow its list of magic
attributes in future versions, user code should generally
refrain from using this convention for its own use. User code
that aspires to become part of the infrastructure could combine
this with a short prefix inside the underscores,
"class-private" (double leading underscore) basically means extra effort is
expended in making the variable hard to see. It's still not enforced, though.
This is easiest to explain with an example:
>>> class Foo(object):
... __x = 3
... def p(self):
... print self.__x
>>> f = Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Foo' object has no attribute '__x'
Google for python name-mangling if you want to know more about this :-)
More information about the Tutor