about if __name == '__main__':

Ian Kelly ian.g.kelly at gmail.com
Mon Aug 29 01:55:39 CEST 2011


On Sun, Aug 28, 2011 at 12:56 PM, woooee <woooee at gmail.com> wrote:
> Two main routines, __main__ and main(), is not the usual or the common
> way to do it.  It is confusing and anyone looking at the end of the
> program for statements executed when the program is called will find
> an isolated call to main(), and then have to search the program for
> the statements that should have been at the bottom of the program.

Not a problem if you write them one after another.  Besides which, any
decent editor will have a command to go directly from the function
call to the function definition, so I really don't see this as a
problem.

> The only reason to use such a technique in Python is if you want to
> call the function if the program is run from the command line, and
> also call the same function if the program is imported from another.

Or if your main "routine" has variables, and you don't particularly
want them polluting the module's global namespace.

> In which case, use a name that is descriptive, not "main".

"main" is descriptive in that it clearly designates the entry point of
the script to anybody accustomed to such terminology.  But there is
certainly no reason it needs to be "main", and in fact I only used
that for the example.  In an actual script I would use whatever seems
appropriate.



More information about the Python-list mailing list