[Tutor] Notepad++ question
Emile van Sebille
emile at fenx.com
Fri Jun 15 01:19:20 CEST 2012
On 6/14/2012 3:18 PM Alexander Quest said...
> [Resending because I messed up on last email]
>
> My question was regarding a piece of boilerplate code:
>
> if __name__ == '__main__':
> main()
>
__name__ within a python module is either '__main__' when invoked
directly from a command line, or contains the module name. This allows
the module to sense if it was imported or run directly and perform any
relevant code that may depend on that. One common use is to run test
code within libraries intended to be imported.
This illustrates the difference:
$ cat > test.py
if __name__ == '__main__':
print "__name__ == '__main__'"
else:
print "__name__ == '",__name__,"'"
Emile at MIS2 ~
$ python test.py
__name__ == '__main__'
Emile at MIS2 ~
$ python
Python 2.4.3 (#1, May 18 2006, 07:40:45)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
__name__ == ' test '
>>>
> 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
More information about the Tutor
mailing list