Please explain Python "__whatever__" construct.

Matimus mccredie at gmail.com
Mon Jun 16 19:24:34 EDT 2008


When and why would I ever use
> "__main__" or the many other "__whatever__" constructs?

You don't generally use those names directly, they are 'magic'. The
__add__ example is a good one. When you do `"hello " + "world"` behind
the scenes python is actually calling "hello ".__add__("world").

There are a couple of places though that you do use them. "__main__"
is a good example. That is the name of the `main` module. The module
attribute `__name__` is the name of that module. If the code is being
executed as a script the value of `__name__` is set to "__main__".
Hence, if you create a module and you want to execute some code only
if that module is run as a script you can use this construct:

if __name__ == "__main__":
 # do stuff

Here is an example of a the `__name__` attribute when it isn't
"__main__":

>>> import sys
>>> sys.__name__
'sys'

Also, these names are frequently used when creating a class where you
want special behavior.

>>> class myint(object):
...  def __init__(self, a): # The constructor
...   self.a = a
...
...  def __add__(self, x):
...   print "I'm adding"
...   return self.a + x
...
>>> x = myint(10)
>>> x + 12
I'm adding
22

As an added note, `"hello " "world"` is not concatenating two strings,
The parser just sees it as one string. Otherwise, this would also
work:

>>> x = "hello "
>>> x "world"
  File "<stdin>", line 1
    x "world"
            ^
SyntaxError: invalid syntax

Where:

>>> x = "hello "
>>> x + "world"
'hello world'

Matt



More information about the Python-list mailing list