Request for feedback on my first Python program

Andrew Walkingshaw andrew-usenet at lexical.org.uk
Fri May 30 10:44:24 EDT 2003


In article <bb7m5j$282$1 at panix1.panix.com>, 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__':".

Thanks; hadn't considered that point. (Part of the value of trying to
be helpful in c.l.py, I've found, is that the most experienced
programmers take time to correct the efforts to help as well as
answering the question in the original post!)

Am I right in thinking that this is because this main()
is useless in the event of reusing this program as a module? That would
seem to be the obvious case where this would blow up nastily.

Hence, I guess the program should read:

def main(filename):
    f = open(filename, "r")
    [...]

if "__name__" == "__main__":
    if len(sys.argv) != 2:
        usage(sys.argv[0])
    main(sys.argv[1])

- or something similar. Please correct me if I'm still misguided :)

- Andrew

-- 
Andrew Walkingshaw | andrew-usenet at lexical.org.uk





More information about the Python-list mailing list