Need help optimizing first script

Steven Taschuk staschuk at telusplanet.net
Fri Jun 20 02:05:32 CEST 2003


Quoth John J. Lee:
> popup391 at yahoo.com (Frederic Lafleche) writes:
> > [...]  As this is my first script, I'm looking for ways to improve code
> > in any possible way, whether it's overall design, style, grammar,
> > logic, readability, performance, validation, anything.

Impressive for a first script!

> > # Map network drive
> > def use (drive, host, user, passwd):
> >     try:
> >         WNetAddConnection2 (1, drive, host, None, user, passwd)
> >         return 0
> >     except error:
> >         return 1
> 
> Apart from the comment where there should be a docstring, OK.  [...]

I'll disagree with John here, not about the comment/docstring
thing, but about this function being otherwise okay.  It seems to
be following the C convention of returning zero for success and
nonzero for failure.  I'd suggest letting the exception propagate
instead, catching it only when you want to do error reporting --
which is all you use this return value for anyway.  This saves you
the risk of forgetting to check the return value, which is one of
the major benefits of exceptions.

Thus:

    def use(drive, host, user, passwd):
        WNetAddConnection2(1, drive, host, None, user, passwd)

and later,

    try:
        if devicename[0] not in drives:
            use(devicename, sharename, username, password)
    except error:
        fObject.write('Cannot map device.\n')
        sys.exit(1)

for example.  It might even be fine to let the exception propagate
even further, killing the script entirely and printing the normal
traceback.  Then this later bit would be simply

    if devicename[0] not in drives:
        use(devicename, sharename, username, password)

Whether this would be desirable depends on whether the user of the
script needs a friendlier error message than a traceback.

-- 
Steven Taschuk                                     staschuk at telusplanet.net
Receive them ignorant; dispatch them confused.  (Weschler's Teaching Motto)





More information about the Python-list mailing list