[Tutor] __name__=='__main__'

Alan Gauld alan.gauld at btinternet.com
Tue Feb 21 01:17:21 CET 2012

On 20/02/12 23:46, Michael Lewis wrote:

> I am having some trouble understanding how to use __name__== '__main__'.
> Can you please give me some insight?

Others have told you how to fix it. The insight is that when
you import a python file its __name__ attribute is set to the module 
name. When you run it as the top level script its __name__ is set to 

So you want to create an 'if' test, and it can be anywhere in your code 
there is nothing special about it, but usually it's at the bottom of the 
file and looks like:

def moduleFunc()
    # this is the code that gets used as a module

def anotherFunc():
    #and so is this

def main():
    # put your main program code here
    # it doesn't get run if the file
    # is imported
    #   - unless the user chooses to explicitly of course!

if __name__ == "__main__":
# or call it test() if the file is only expected to be used as a module


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list