Double underscore names

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Feb 13 13:21:47 CET 2008


On Wed, 13 Feb 2008 09:55:39 +1100, Ben Finney wrote:

> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> 
>> having the ability to create a protocol is a Very Good Thing, and
>> double leading and trailing underscore names are the accepted Python
>> style for such special methods.
> 
> Is it? There are many protocols that use plain names. Even the built-in
> types support many "protocol" operations via plain-named attributes.
> 
>     dict.get, dict.items, dict.keys, dict.values
> 
>     list.insert, list.append, list.extend, list.remove

I don't believe any of those define a protocols. They are merely methods. 
An example of a protocol would be dict.__getitem__(): you can retrieve 
items from any object using the square bracket syntax if it has a 
__getitem__ method.

However, having said that, I find myself in the curious position of 
(reluctantly) agreeing with your conclusion to "Go ahead and implement 
your protocol using attributes with plain names" even though I disagree 
with virtually every part of your reasoning. In my mind, the two deciding 
factors are:

(1) Guido's original style guide essay allowed developers to use double-
underscore names under certain circumstances. It seems that this has been 
deliberately dropped when it became a PEP.

http://www.python.org/doc/essays/styleguide.html#names

(2) PEP 3114 "Renaming iterator.next() to iterator.__next__()" makes it 
explicit that names of the form __parrot__ are intended to be "a separate 
namespace for names that are part of the Python language definition".

Given that, I think that the special name __test__ in the doctest module 
is possibly an anomaly: it's not part of the language, but it seems to 
have the BDFL's blessing, or at least the BDFL didn't notice it. It's 
hardly the only anomaly in the standard library though, so one shouldn't 
draw too many conclusions from it. I think the intention is clear: names 
like __parrot__ are strictly verboten for user code.

If and when my modest little programming efforts are considered for 
inclusion in the standard library, I will rethink this issue. In the 
meantime, no more __parrots__.

You can stop reading now. But for those who care, I have a few final 
comments.



>     file.read, file.write, file.close

I would accept that these three are part of the "file object protocol", 
However, they seem to be the odd one out: every other Python protocol 
that I can think of uses the __parrot__ form.

iterator.next() is the exception, but that's explicitly been slated for 
change to __next__() in Python 3.


-- 
Steven



More information about the Python-list mailing list