Python's equivalent to Main calling program and subprograms

Bill Allen wallenpb at gmail.com
Wed Dec 1 22:39:01 EST 2010


Thanks for the explanation of "main".   Some tutorials mention it, some
don't.   I have written some not trial Python programs and have never had a
real need to use that convention, but at least I understand it now.

--Bill

On Wed, Dec 1, 2010 at 1:13 PM, Tim Harig <usernet at ilthio.net> wrote:

> > On Wed, Dec 1, 2010 at 9:08 AM, m b <snert at hotmail.se> wrote:
> >>> > if __name__ == "__main__":
> >>> > main()
> >>
> >> What does this mean?
>
> It is a Python idiom and a good practice.  Strictly speaking it is
> unnecessary.  Python doesn't recognize any functional initialization
> vector other then the start of the file.  When Python loads a module,
> it executes anything it finds in the module scope (Anything not in the
> body of a class or function declaration).  Using a main function is just
> a convention.  You could just place all of your main level code in the
> module scope:
>
> def Subprogram1():
>        # code
> def Subprogram2():
>        # code
> def Subprogram3():
>        # code
>
> # main code
>
> or equivilantly, always execute main():
>
> def Subprogram1():
>        # code
> def Subprogram2():
>        # code
> def Subprogram3():
>        # code
> def main():
>        # main code
> main()
>
> Both are valid from Python's point of view.
>
> The 'if __name__ == "__main__":' idiom is used, because it allows the
> module to be loaded without running main().  This is useful if you wanted
> to use Subprogram2() from another program.  Even if you don't forsee using
> any of the subprograms (functions to Python), this can be useful when
> writing test code as you can import the program as a module to test its
> classes or functions separately.
>  --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101201/6b5d95dd/attachment.html>


More information about the Python-list mailing list