Why all the __double_underscored_vars__?

Chris Rebert clp2 at rebertia.com
Fri Aug 7 18:13:41 EDT 2009


On Fri, Aug 7, 2009 at 5:51 PM, kj<no.email at please.post> wrote:
> Python is chock-full of identifiers beginning and ending with double
> underscores, such as __builtin__, __contains__, and __coerce__.
>
> Using underscores to signal that an identifier is somehow "private"
> to an implementation is pretty common in languages other than
> Python.  But in these cases the understanding is that the use of
> these variables in external code amounts to "going behind the API",
> and is therefore unwise.
>
> But as far as I can tell, Python's double-underscore variables are
> very much part of Python's API.  E.g., programmers are specifically
> instructed to override "double-underscore methods" to achieve
> certain functionalities.

Right, but the *users* of the functionality provided by __methods__
typically should not invoke such methods directly.
For example, one should write `a > b`, not `a.__gt__(b)`. The lack of
underscores in just plain `gt` would suggest that it's a normal method
that could/should be called directly. Also, if the underscore
requirement were removed, then people might unknowingly overload an
operator without knowing it.
The double-underscores indicate that the Python interpreter itself
usually is the caller of the method, and as such some level of "magic"
may be associated with it. Other languages have you do the equivalent
of `def +():` or `def operator +()` to override an operator, the
keyword or symbol serving a similar warning that "here be magic". To
avoid adding another keyword and the confusion of having punctuation
as method names, Python uses a different convention, double leading
and trailing underscores.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list