OSDir


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

about main()


On 05Jul2018 11:22, Rhodri James <rhodri at kynesim.co.uk> wrote:
>On 05/07/18 09:43, Abdur-Rahmaan Janhangeer wrote:
>>just when to use main() in
>>
>>if __name__ == '__main__' :
>>     main()
>>
>>is far is it good in py?
>>
>>or should file intended to be run just not include it?
>
>It's a matter of taste.  If your "file intended to be run" also 
>contains things that might be useful as a module, use the "if __name__ 
>== '__main__'" trick.  Otherwise it can be more of a distraction than 
>a help.  I'm not a big fan of "main()" functions myself; creating a function 
>which will be called exactly once seems rather wasteful.

I almost always make a main. For several of my modules there's a meaningful 
command line mode, and for most of the rest I make main run the self tests.

The main function has some advantages:

- I put it at the top of the module, before anything other functions: that way 
  the "main" operation of the module, if there is one, is in your face them you 
  open the file, easy to find. Also, it is _immediately_ apparent that this 
  module has a "main programme" mode.

- You don't need to call it just once. Making a main() function, should it make 
  sense, lets you call it _from other code_. Consider a wrapper which relies on 
  the main function of this module for the core command line operation, or 
  which runs this module's main as some kind of "subcommand" in a larger tool, 
  such as most VCS commands, GraphicsMagick, etc - all have subcommandswhich 
  are effectively standalone things in their own right.

I also advocate making the boilerplate like this:

  if __name__ == '__main__':
    sys.exit(main(sys.argv))

and make main() like this:

  def main(argv=None):
    if argv is None:
      argv = sys.argv
    ... code here ...
    return meaningful_exit_code

The "argv is None" shuffle is for PyPI packaging, where the standard script 
wrapper _doesn't_ pass in sys.argv, (no idea why, I should submit an 
enhancement proposal). Otherwise, there's argv, ready for reuse of the main() 
function from arbitrary code.

Cheers,
Cameron Simpson <cs at cskk.id.au>