When I need classes?

Cameron Simpson cs at zip.com.au
Sun Jan 10 21:57:41 EST 2016


On 10Jan2016 08:02, Michael Torrie <torriem at gmail.com> wrote:
>I can't speak to Flask or any other web development.  But for simple
>scripts, I'll start out with no classes.  Just functions as needed, and
>some main logic.  I always use the idiom:
>
>if __name__ == '__main__':
>    # do main logic here
>
>This way I can import functions defined in this script into another
>script later if I want.

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.

Cheers,
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list