[Tutor] PyScripter header?

Steven D'Aprano steve at pearwood.info
Wed May 8 13:37:54 CEST 2013


On 08/05/13 18:10, Jim Mooney wrote:

> However, a new file in PyScripter always starts with:
> _____________________________________________
>
> def main():
>      pass
>
> if __name__ == '__main__':
>      main()
> _____________________________________________
>
> What is that stuff?  I thought I was getting away from all this
> business of defining a main entry point. I don't see it in any of the
> Py library files or other Py programs.


It's optional, but good practice, to separate your main program out into a separate subroutine.

Of course, Python is a pragmatic language, and you can write a plain script that just does what you want directly:


=== start file ===

# A rubbish script :-)
import sys
if sys.argv[1] == "hello":
     print "And hello to you too!"
else:
     print "Bah, why don't you say hello?"

=== end file ===


That's fine if all you are doing, ever, is running the script. But for more interesting scripts, it can be useful to design it so that you can both run the script directly, and import it as a Python module. Perhaps to re-use some of the components, or for testing, or to use at the interactive interpreter.

So in this case, you should factor out the main script and guard it with a "if __name__ == '__main__' clause. That's certainly not compulsory, but it is good practice. Naturally you don't have to call the main function "main".

Are you aware of what the "if __name__" bit does?

There is a global variable called __name__. Whenever a module is imported, Python automatically sets the __name__ variable to the name of the module, minus any .py or other extension. With one exception: when you are running a module as a script, Python does a little trick: it sets __name__ to the magic value "__main__" instead of the module's actual name. So a module can tell if it is being run as a script by looking at the global variable __name__ and seeing if it is equal to "__main__".

Yes, it is a bit of a hack, but it works acceptably most of the time.



-- 
Steven


More information about the Tutor mailing list