Python file structure

Tim Chase python.list at tim.thechases.com
Wed May 13 14:34:22 EDT 2015


On 2015-05-13 06:07, Chris Angelico wrote:
> On Wed, May 13, 2015 at 5:54 AM, Ian Kelly <ian.g.kelly at gmail.com>
> wrote:
> > Also, I like to put command-line parsing inside the main function
> > and make that its *only* responsibility. The main function then
> > calls the real entry point of my script, which will be something
> > more specifically named. This also has the advantage that if some
> > other module needs to invoke my script, all it has to do is call
> > the entry point function which will be named something more
> > suitable than "main".
> 
> That often makes sense, but sometimes doesn't. When it doesn't, you
> can usually tell because your main function looks something like
> this:
> 
> def main():
>     do_real_work(*sys.argv)
> if __name__=="__main__": main()
> 
> A one-line function that's called from one place? In-line it.
> 
> if __name__ == "__main__":
>     do_real_work(*sys.argv)

Usually mine look something like

  def do_real_work(options, args):
    ...
  def main():
    parser = [optparse,argparse,docopt]....
    options, args = parser.parse_args()
    do_real_work(options, args)
  if __name__ == "__main__":
    main()

since my real-work function usually relies on configuration
(sometimes this also includes a config-file or environment variables
being munged into some "options" data structure).

-tkc



  



More information about the Python-list mailing list