[Tutor] Notepad++ question

Dave Angel d at davea.name
Fri Jun 15 01:08:32 CEST 2012


On 06/14/2012 06:18 PM, Alexander Quest wrote:
> [Resending because I messed up on last email]
> 
> My question was regarding a piece of boilerplate code:
> 
> if __name__ == '__main__':
>   main()
> 
> This calls the main function, but I don't understand what the 'if'
> statement is doing here. In the simple programs that I've seen this so far,
> there is no variable called "_name_", and even if there was, why is it
> comparing it to "_main_"? Why can't the main function just be called by
> typing main()- why do we need this if statement to precede it? Thanks.
> 
> -Alex
> 

It may not matter for simple scripts.  But many times the same file is
used in two ways.  When it's used as a script, __name__ is set to the
literal "__main__"

But when it's used as a module (ie. somebody imports it) then the name
is set to the module name (filename without the .py)

So, you normally do not want to execute your main() function unless it's
being used as a script.

This becomes very important when you want to reuse code, or when you
want to write test cases for modules.


-- 

DaveA


More information about the Tutor mailing list