[Tutor] telling dir(_builtins_) from dir(__builtins__)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 14 Mar 2002 09:41:05 -0800 (PST)


On Thu, 14 Mar 2002, john public wrote:

> How in the heck is a Newwbie to know dir(_builtins_) from
> dir(__builtins__)?!? both look like one hypen to me. One's just longer
> than the other. I just assumed it was a difference between the type on
> my machine and the type in the O'riely book.

Typography can be a tricky thing.  '1' and 'l' and 'i' look much too
similar, as does '0' and 'O'.  Whoever typeset the book you're looking at
should probably have made it look more visually distinctive, but, on the
other hand, double underscores already suggest tricky magic ahead...
*grin*


(By the way, newcomers really aren't expected to look into '__builtins__'
until they have more experience; it is often possible to not even know
that it exists unless we read closely into the "separate symbol table"  
mentioned in the library documentation:

    http://www.python.org/doc/lib/builtin.html)


Double underscores in Python indicate that here, in front of us, is a
variable that probably means something special to Python.  This
double-underscore convention in Python isn't a one-time special case;
Python uses it for reserved names and special variables specific to Python
itself.

Newcomers often encounter the __double_underscore__ when they try to
"overload" operators with classes.  For example, here's a class that has
some strange looking functions defined in them:

###
class ModuloNumber:
    def __init__(self, x, n):
        self.x, self.n = x%n, n

    def __str__(self):
        return '%d modulo %d' % (self.x, self.n)

    def __add__(self, some_number):
        return ModuloNumber(self.x + some_number, self.n)
###


Here's an example of what this is sorta doing:

###
>>> my_number = ModuloNumber(5, 12)
>>> str(my_number)
'5 modulo 12'
>>> for i in range(10):
...     print my_number + i
... 
5 modulo 12
6 modulo 12
7 modulo 12
8 modulo 12
9 modulo 12
10 modulo 12
11 modulo 12
0 modulo 12
1 modulo 12
2 modulo 12
###

So something sorta strange is happening here: somehow, Python is calling
the '__add__()' function when we say 'Add my_number to i'.  __str__ and
__add__ are special method names meant for its own nefarious purposes:

    http://www.python.org/doc/current/ref/specialnames.html

There aren't many other places where we'll see double underscores, but at
least they're used consistantly.


> So far this is the first thing I have found like this in Python. I
> have actually been amazed at how easy it is compared to C++ which I
> worked at for 2 months and got relatively nowhere by comparison. I am
> sure glad Barry Warsaw steered me towards Python.

When you see double underscores, think "having some special meaning to
Python itself".  I don't believe anyone wanted to make '__' to look like a
single '_', but that's probably more of a case of bad typography rather
than bad programming.  *grin*


Best of wishes to you!