[Tutor] Beginner Q: What does the double underscore mean __ ?

Dave Angel d at davea.name
Sun Sep 9 14:38:55 CEST 2012

On 09/09/2012 08:16 AM, Aaron Pilgrim wrote:
> Thank you for the response!

You're welcome. A couple points of order:  please don't top-post.  There
is a standard here, which makes much more sense than the
Microsoft-imposed  "put everything backwards" approach.  Put your new
text AFTER whatever you're quoting.  Or don't bother quoting.

Second:  it's impolite to post a second copy of a question 20 minutes
after a first, especially on two closely related forums like
comp.lang.python and tutor.  Wait till you're sure you won't get a
response (on these forums, that might be 24 hours).  By posting twice,
you get two separate threads, and lots of duplicate information.

> It makes much more sense to me. I read the python documentation and
> was a little confused. I was gathering it was for operator
> overloading-that there was already a main and already a name function
> and these were special cases.

Now you're asking specifically about the __name__ attribute.  That
exists in all modules, and is simply the file name that was imported
(without path and such).  And it's filled in for the script as well, but
given a unique value, regardless of the script's filename.

The PURPOSE, however, is to let programs tell whether a particular
source file was loaded as a script, or imported as a module.  It's a
common paradigm for modules to do self-testing when the source is loaded
as a script.  But you don't want that self-test code to be live when
some other program uses the module.  So you wrap it in the if statement:

if __name__ == "__main__":
    if myfunc("abc") != 3:
        error("myfunc is busted"



More information about the Tutor mailing list