Total newbie question: Best practice

Chris Angelico rosuav at gmail.com
Tue Nov 29 15:36:35 EST 2011


On Wed, Nov 30, 2011 at 7:06 AM, Colin Higwell <colinh at somewhere.invalid> wrote:
> However, they are monolithic in nature; i.e. they begin at the beginning
> and finish at the end. Having done a little reading, I note that it seems
> to be quite common to have a function main() at the start (which in turn
> calls other functions as appropriate), and then to call main() to do the
> work.

The reason for this practice is to allow your .py file to be either a
top-level program or an imported module.

if __name__ == "__main__":
    main()

When you run a .py file directly, __name__ will be "__main__", and
it'll execute main(). (Some programs directly embed the main routine
in that if block - appropriate if main() would be very short, eg just
calling some other function.) But if you import it as a module in some
other program, that won't be the case; so instead, the module's
functions are made available to the calling program.

For simple scripts that don't have anything to offer as a module, it's
fine to not bother with this structure. Python doesn't demand
syntactic salt; that's one of its greatest features, IMHO.

Chris Angelico



More information about the Python-list mailing list