[Tutor] The IF statement

Kent Johnson kent37 at tds.net
Thu Sep 6 00:03:36 CEST 2007

Toby Holland wrote:
> Hi gang,
> Just doing what I can to understand as I study
> I have been reading about testing modules this is the statement that I 
> have been given
> if __name__ == "__main__":
> I understand that all modules have a built in attribute __name__, but 
> what does the __main__ have to do with this attribute.  Is it saying 
> that __name__ is the same as __main__?

Yes. Note that __name__ is a variable and "__main__" is a string. So 
this says that the value of the variable __name__ is the string "__main__".

> I know that if the module is imported then __name__is the moules file 
> name,

It is the module name which is not quite the same as the file name. 
__file__ has the file name.

> but is this just for the script that your writing while using that 
> module or is it just to show that the module was imported?

It is a way to tell if the module was imported or run directly as a script.

> correct me if I'm wrong please, the modules file name is __main__ when 
> its being used as a stand alone program?

The modules name, not the file name; otherwise yes.

> If this is the case the difference is whether or not the module is a 
> program by itself or intigrated with a script that is what determines 
> its name (i.e. __name__ and __main__)


It is handy to be able to write a module so it can be used by being 
imported into another module, or by being run on its own. When run on 
its own it might provide a simple command line interface or run unit 
tests or whatever the developer finds useful. When imported as a library 
for another module then this behaviour is not wanted so it is hidden by the
   if __name__ == '__main__':


More information about the Tutor mailing list