breaking from loop

Peter Otten __peter__ at web.de
Sun Feb 12 09:48:36 EST 2006


Ritesh Raj Sarraf wrote:

> def copy_first_match(repository, filename, dest_dir): # aka
> walk_tree_copy()
>     for path, file in files(repository):
>         if file == filename:
>             try:
>                 shutil.copy(os.path.join(path, file), dest_dir)
>                 sys.stdout.write("%s copied from local cache %s." %
> (file, repository))
>             except shutil.Error:
>                 sys.stdout.write("%s is available in %s. Skipping
> Copy!" % (file, dest_dir))
>             return True
>     return False
> 
> All I've added is the exception check because in case "file" is
> available in "dest_dir", I want to display a message.
> Since I'm still new and learning will be great if you let me know if
> this is the proper way or not.

I prefer to let the exception propagate. As you wrote it, the code calling
copy_first_match() has no way of knowing whether a file was copied or not.

If you don't want to bother with exceptions in the calling code I'd slightly
modify the try...except:

try:
   # copy
except (shutil.Error, OSError), e:
   # print failure message
   return False

I. e.

- catch OSError, too. I think shutil.copy() is more likely to raise an
OSError than a shutil.Error.
- return False if an exception occurs. That way you can test if something
went wrong like so:

if not copy_first_match(...):
    print "file not found or unable to copy it"

Peter




More information about the Python-list mailing list