[Python-Dev] defaultdict and on_missing()

Michael Chermside mcherm at mcherm.com
Fri Feb 24 03:39:56 CET 2006

Walter Dörwald writes:
> I always thought that __magic__ method calls are done by Python on
> objects it doesn't know about. The special method name ensures that it
> is indeed the protocol Python is talking about, not some random method
> (with next() being the exception). In the defaultdict case this isn't a
> problem, because defaultdict is calling its own method.

I, instead, felt that the __xxx__ convention served a few purposes. First,
it indicates that the method will be called in some means OTHER than
by name (generally, the interpreter invokes it directly, although in this
case it's a built-in method of dict that would invoke it). Secondly, it serves
to flag the method as being special -- true newbies can safely ignore
nearly all special methods aside from __init__(). And it serves to create
a separate namespace... writers of Python code know that names
beginning and ending with double-underscores are "reserved for the
language". Of these, I always felt that special invocation was the most
important feature. The next() method of iterators was an interesting
object lesson. The original reasoning (I think) for using next() not
__next__() was that *sometimes* the method was called directly by
name (when stepping an iterator manually, which one frequently does
for perfectly good reasons). Since it was sometimes invoked by name
and sometimes by special mechanism, the choice was to use the
unadorned name, but later experience showed that it would have been
better the other way.

-- Michael Chermside

More information about the Python-Dev mailing list