Request for feedback on my first Python program

Peter Hansen peter at engcorp.com
Fri May 30 12:38:34 EDT 2003


Aahz wrote:
> 
> In article <slrnbdeevn.694.andrew-usenet at athena.jcn.srcf.net>,
> Andrew Walkingshaw  <andrew-usenet at lexical.org.uk> wrote:
> >
> >def main():
> >    if len(sys.argv) != 2:
> >        usage(sys.argv[0])
> >    f = open(sys.argv[1], "r")
> 
> This is generally a Bad Idea; your functions should be generic and
> sys.argv handling should be done under "if __name__=='__main__':".

I don't entirely agree.  Although I can see calling main as 

   if __name__ == '__main__':
       main(sys.argv[1:]) 

anything more than this seems less readable.  This has the added
advantage of preventing readers and maintainers from getting confused 
because of the differences between code at module level (where what feels 
like a local is actually module-global), and in a function like main() 
where locals are very clearly local.  I've seen __main__ blocks which
are far too ugly to read, mainly because they are at module level instead
of function-local.

I'm actually inconsistent about this myself, but I don't think
the advice Aahz gives here is necessarily a defacto standard.
(Or is it?  I haven't sampled enough code to know for sure.)

-Peter




More information about the Python-list mailing list