[Tutor] Which is better Practice and why

Steven D'Aprano steve at pearwood.info
Tue Oct 23 00:15:06 CEST 2012

On 22/10/12 22:45, Matthew Ngaha wrote:
> In many of the tutorial examples ive come across, the main code's program
> is never at the top level, but always in a function of some sort. i
> understand why but, there is always a different way used to access the main
> code, i want to know which is the best.
> main()
>       main's code
> #top level
> main()

Not that. That unconditionally executes main the first time you access
the module, *regardless* of whether it is being run as a script or
being imported. That is nearly always the wrong thing to do.

It's particularly awful because importing the module for a second time
will not re-run the main program. You have to exit Python, restart it,
and then re-import the module again.

> they call the main program by simply calling the main function. I've also
> seen a more complcated:
> if __name__ == '__main__':
>      main()

This one is best. It only runs the main function when the module is being
run as a script.

> the 2nd one usually includes a lot more code then i showed.

Yes, that's because when people write proper scripts, they tend to write
code for handling errors, checking the command line arguments, etc. When
people just slap together a lazy "always execute the main function", they
tend to not bother.

Or perhaps that's just how I work :)


More information about the Tutor mailing list