When I need classes?

Chris Angelico rosuav at gmail.com
Sun Jan 10 22:19:12 EST 2016


On Mon, Jan 11, 2016 at 1:57 PM, Cameron Simpson <cs at zip.com.au> wrote:
> I always structure this aspect as:
>
>  ... at or near top of script ...
>
>  def main(argv):
>    ... do main logic here ...
>
>  ... at bottom ...
>  if __name__ == '__main__':
>    sys.exit(main(sys.argv))
>
> This has the benefits of (a) putting the main program at the top where it is
> easy to see/find and (b) avoiding accidently introduction of dependence on
> global variables - because verything is inside main() it has the same
> behaviour as any other function.
>

Personally, I like to put 'def main()' at the bottom of the script, on
the principle that, as much as possible, code should refer to stuff
higher up rather than lower down. But otherwise, I agree. Your "if
__name__" block is just the glue between sys.{argv,exit} and your main
function, and that's how it should be.

ChrisA



More information about the Python-list mailing list