Every module has a name and statements in a module can find out this name. This is especially handy in one particular situation. As mentioned previously, when a module is imported, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported as a module? This can be achieved using the __name__ variable.
Example 8.2. Using a module's __name__
#!/usr/bin/python # Filename : using__name__.py if __name__ == '__main__': print 'I am here only if this program is run by itself' print 'and not imported as a module'
$ python using__name__.py This is run only if this program is run by itself and not imported as a module $ python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import using__name__ >>>
Every Python module/program has a variable defined called __name__ which is set to '__main__' when the program is run by itself. If it is imported to another program, it is set to the name of the module. We make use of this to run a block of statements only if the program was run by itself.