Please explain Python "__whatever__" construct.

s0suk3 at gmail.com s0suk3 at gmail.com
Tue Jun 17 01:20:01 CEST 2008


On Jun 16, 4:56 pm, bsag... at gmail.com wrote:
> After a couple of weeks studying Python, I already have a few useful
> scripts, including one that downloads 1500 Yahoo stock quotes in 6
> seconds. However, many things are puzzling to me. I keep on seeing
> things like "__main__" in scripts.  A more obscure example would be
> "__add__" used in string concatenation. For example, I can use "Hello
> "+"world (or just "Hello" "world") to join those two words. But I can
> also use "Hello ".__add__("world"). When and why would I ever use
> "__main__" or the many other "__whatever__" constructs?

Generally, names with two leading and trailing underscores signal
something "internal". Though the string "__main__" is rather something
else: the variable __name__ is set to the string "__main__" when a
script is run as a script (i.e., is not imported). The convention is
also common in built-in object methods, such as the one you mentioned:
the built-in type str's __add__() method. Personally, I usually try to
avoid using such methods directly, because, as I said, they're rather
for internal use or for special functionality. For example, when the
expression '"hello" + "world"' is evaluated, it's likely that Python
is calling one of the string's __add__() method internally to perform
the "addition." So I'd recommend that you don't use those methods
unless you absolutely need direct access to their functionality.



More information about the Python-list mailing list