A neat trick

Guido.van.Rossum@cwi.nl
Wed, 26 Jan 1994 15:31:40 +0100

While writing the NEWS file for release 1.0.0, a neat trick just
occurred to me. Many people want to write modules that call a main()
function when the module is run as a script. Common wisdom was that
to do this you would need to compare the last path component
(basename) of sys.argv[0] without the ".py" suffix to the (assumed)
module name. This was a lot of code and not entirely foolproof (the
module or the script might be renamed or accessed via a symbolic link).

In 1.0.0, where a module can get its own true name as __name__, a much
simpler test is possible:

if __name__ == '__main__':
# We are being run as a script
main()
# else we are being imported as a module

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>