return statement in functions

Francis Avila francisgavila at yahoo.com
Mon Dec 22 20:56:28 EST 2003


hokiegal99 wrote in message
<93f5c5e9.0312221718.23e42dac at posting.google.com>...
>I was told earlier (w/o explanation) that functions should return
>something. I was under the impression that it was OK with Python to
>leave the return statement off.

Functions return something in Python, by definition.  If you leave the
return statement off, Python inserts an implicit 'return None' to the end of
the text of your function.

> Could someone enlighten me on why or
>why not to use a return statement when defining functions?

This is a philosophic question.  The final end of a function is to take
input and return output which is somehow based upon that input.  The
functional *construct* can be abused every which way (often validly) to
violate any part of that statement: it can take arguments which don't
matter; it can return things which are unrelated to the arguments; it can
have all sorts of side effects that the caller isn't interested in, etc.

>Below is
>the bit of code I was told should return something:
>
>def fs_object_count(path):
>   file_count = 0
>   dir_count = 0
>   for root, dirs, files in os.walk(path):
>      file_count += len(files)
>      dir_count += len(dirs)
>   print "Number of Files Examined: ", file_count
>   print "Number of Folders Examined: ", dir_count
>   print "Total Number of FS Objects:", file_count + dir_count

The code is in poor style simply because it does multiple things at once in
a way that is not terribly modular: namely, it does file/dir counts, and it
prints results.

Better would be this:

def fs_object_count(path):
    """Return (numdirs, numfiles) in path and its subdirectories."""
    file_count = 0
    dir_count = 0
    for root, dirs, files in os.walk(path):
        file_count += len(files)
        dir_count += len(dirs)
    return dir_count, file_count

dn, fn = fs_object_count('mypath')
print "Number of Files:", fn
print "Number of Directories:", dn
print "Total:", fn+dn

You can have more complex/prettier output logic if you want, but the point
is to make your functions as general as possible, while doing only one
thing.  (And that's not a contradiction!)
--
Francis Avila





More information about the Python-list mailing list