[Tutor] Comments appreciated

Jeff Shannon jeff at ccvcorp.com
Wed Dec 22 03:06:02 CET 2004


Luis N wrote:
> This is the most meaningful thing this newbie has ever done. Comments
> are appreciated:

Okay, here's a few thoughts...

> junk = []
> for arg in sys.argv:
>     junk.append(arg)
> 
> junk = junk[1:]

You can write these four lines much simpler as:

junk = sys.argv[1:]



> if len(junk) is 0 and empty == False:
>     sys.exit()    
> else:
>     if len(junk) > 0:
>         trash(junk)
>     if empty == True:
>         can()

You can simplify this, too.

If empty is True, then you want to call can() regardless of whether 
you're doing anything else.  You can handle that first, and *then* see 
whether there's junk to delete.  This also means that, if you don't 
have junk to delete, you can simply do nothing, instead of explicitly 
calling sys.exit().  In addition, you don't need to explicitly test 
against True -- empty will already be true or false on its own, so 
comparing it inside an if statement doesn't gain you anything.

if empty:
     can()
if len(junk) > 0:
     trash(junk)


Also, even though this is intended to be a quick shell script, it's 
not a bad idea to make everything except function defs into a little 
main() function, and call it in a script-only section.  This gives you 
a bit more modularity, pulls all of your actions into a single place, 
and lets you avoid using global variables.

def main(junk):
     trashcan = os.path.expanduser("~/.trashcan")

     empty = False
     if "-e" in junk:
         empty = True
         junk.remove("-e")

     if not os.path.exists(trashcan):
         os.mkdir(trashcan)

     if empty:
         can()
     if len(junk) > 0:
         trash(junk)

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


Notice that I've also changed your trashcan from explicitly stating a 
home directory to getting the home directory for whoever the current 
user is.

You can refine main() further, too -- for instance, instead of setting 
an empty flag, you could just call can() as soon as you find the -e 
option.

Jeff Shannon
Technician/Programmer
Credit International



More information about the Tutor mailing list