Why functional Python matters

andrew cooke andrew at acooke.org
Wed Apr 23 19:15:11 EDT 2003


a related question - why does queue have to be passed to helper() in the
code below?  i tried to define it inside walktree (but outside helper)
since it's global to the function, but python objects saying that the
local variable "queue" in helper is accessed before it's defined.  this
seems to be an example of where closures would work perfectly...

#!/usr/bin/python2.2

from __future__ import generators # needed for Python 2.2
import os

def walktree(basepath=".", postorder=True, depthfirst=True,
             ignorelinks=True):

    """Noah Spurrier's code, modified to allow depth/breadth-first
    traversal.  The recursion is there *only* to allow postorder
    processing as the stack rolls back - the rest of the algorithm is
    imperative and queue would be declared outside helper if I knew
    how."""

    # why can't queue be defined here as [basepath] (and then omitted
    # from calls to helper).

    def helper(queue):

        while queue:

            if depthfirst: dir = queue.pop(-1)
            else: dir = queue.pop(0)

            children = os.listdir(dir)

            dirs, nondirs = [], []

            for name in children:
                fullpath = os.path.join(dir, name)
                if os.path.isdir(fullpath) and not \
                       (ignorelinks and os.path.islink(fullpath)):
                    dirs.append(name)
                    queue.append(fullpath)
                else:
                    nondirs.append(name)

            if not postorder:
                yield dir, dirs, nondirs

            if postorder:
                for rest in helper(queue):
                    yield rest
                yield dir, dirs, nondirs

    return helper([basepath])

def test():
     for basepath, dirs, nondirs in \
             walktree(postorder=False, depthfirst=False):
         for name in dirs:
             print os.path.join(basepath, name)
         for name in nondirs:
             print os.path.join(basepath, name)

if __name__ == '__main__':
         test()



tj_scarlet at yahoo.com said:

> mjd at plover.com (Mark Jason Dominus) wrote in message
> news:<b86lc3$tnd$1 at plover.com>...
>> I don't believe that's correct.  At an early Open Source Conference,
>> perhaps around 1998 or so, I was present at a conversation between
>> Guido and Tom Christiansen.  Tom asked Guido why Python didn't have
>> closures, and Guido's reply (and I think this is an exact quote) was
>> "Closures aren't important."
>>
>> I remember it because I was so astonished by the obtuseness of the
>> answer.
>
> Well, it seems the burden of proof is on you.  Please explain the
> usability advantages of closures vs. Python's current scope system.
>
> Tj
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
http://www.acooke.org/andrew





More information about the Python-list mailing list