Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #16404
| References | <jb3e06$37h$1@dont-email.me> |
|---|---|
| Date | 2011-11-30 07:36 +1100 |
| Subject | Re: Total newbie question: Best practice |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3135.1322598998.27778.python-list@python.org> (permalink) |
On Wed, Nov 30, 2011 at 7:06 AM, Colin Higwell <colinh@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Total newbie question: Best practice Colin Higwell <colinh@somewhere.invalid> - 2011-11-29 20:06 +0000
Re: Total newbie question: Best practice Arnaud Delobelle <arnodel@gmail.com> - 2011-11-29 20:34 +0000
Re: Total newbie question: Best practice Neil Cerutti <neilc@norwich.edu> - 2011-11-29 21:12 +0000
Re: Total newbie question: Best practice Chris Angelico <rosuav@gmail.com> - 2011-11-30 07:36 +1100
Re: Total newbie question: Best practice Dave Angel <d@davea.name> - 2011-11-29 16:57 -0500
Re: Total newbie question: Best practice Colin Higwell <colinh@somewhere.invalid> - 2011-11-29 23:08 +0000
RE: Total newbie question: Best practice Shambhu Rajak <Shambhu.Rajak@kpitcummins.com> - 2011-11-30 08:50 +0000
Re: Total newbie question: Best practice "Pedro Henrique G. Souto" <pedro.h.souto@gmail.com> - 2011-11-30 09:36 -0200
csiph-web