[Tutor] if __name__=='__main__' test

Sheila King sheila@thinkspot.net
Thu, 07 Mar 2002 14:17:28 -0800


On Thu, 7 Mar 2002 16:43:10 -0000, "Bruce Gollng" <bwgolling@attbi.com>
wrote about [Tutor] if __name__=='__main__'  test:

> Help please.  I've been studying several books and online tutorials and have been consistently stumped with the  ..  if __name__ == '__main__': test.  No matter when I check __name__ always eq __main__.  So why is this a programming benefit?
> tks
> Bruce Golling (bwgolling@attbi.com)

What I find to be the best feature of the main-name test, is that you can
write a module that is meant to be imported into other programs, but
include a test-suite in it, so that if want to test the module, you run it
as a program itself instead of importing it as a module. In this case, the
__name__ attribute of the module will be '__main__' and it will execute the
testing code. Otherwise, when it is imported as a module, it's name will
not be __main__ and so it will not execute the testing code.

It's just kind of convenient to be able to distribute a module with the
test code built right in that way.

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/