Confused with Underscores in Python

Scott David Daniels Scott.Daniels at Acm.Org
Tue Nov 2 10:54:49 EST 2004


abhay wrote:
> I have really not understood the concept of underscores used in some of the
> methods in python. Is it somewhat smilar to declaring public, private or
> protected methods as in java.

In a way.  Python's "magic" names (those treated specially by the
system) both begin and end with double-underscores.  This rule is
to allow Python's evolution as a language without interfereing with
user-defined names.  The "next" method on iterators should probably
have been "__next__".

A single underscore following a name is used for names that would
naturally be a keyword (class_ for class, for example).

In a class, a method name beginning with a single underscore is a
method is means roughly, "this is an internal method (or variable),
not an interface method.  Don't expect this to work the same way or
even exist in the next version."

A name beginning with a single underscore means roughly, "this is an
internal function, method, or variable, not an interface method.  Don't
expect this to work the same way or even exist in the next version."

In a class, a method or variable name beginning with a double-underscore
(and not ending with a double-underscore) is meant to be class-local.
These names are useful primarily to avoid name conflicts with super-
and sub- classes, as in the cases of "mixin" style programming.
Some programmers use this as a means to "enforce" privacy, but it
really doesn't work -- it is easy to defeat if you care to, and a
single initial underscore should be enough to warn off those who will
cooperate.

-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list