Use apply() or not, and raising multiple exceptions (co-routines?)

logistix logstx at bellatlantic.net
Sun Mar 10 13:06:44 EST 2002


> I could have also written this as:
>
> for check in self.checks:
>     apply (check, [data])
>
> is there any particular reason to prefer one style over the other?

It basically depends on how much you like functional programming.  Generally
people who make lists of functions will prefer using map, apply, and filter.

Even more functional than this is to write your check function to analyze
only one datum at a time.  I imagine each check function currently has a
"for datum in data:" loop as well.  If you design them to analyze one piece
of data at a time you can replace the above with:

for check in self.checks:
    map(check, data)

This will also cycle through the whole list if you handle an exception in
the check function now.  Map also creates a list of return values (this is
actaully the whole point of map) so if you return error codes from the
except: clause you can save them:

def check(datum)
    try:
        # do check stuff
    except IntegrityCheckError, message:
        return message

for check in self.checks:
    errors = map(check,data)
    for error in errors:
        if error != 0:
            print error

And if you really want to go overboard on the functional code, replace the
above with ;)

def checkData(check, data):
    map(sys.stdout.write, filter(lambda x: x != 0, map(check, data)))

[checkData(check,data) for check in self.checks]





More information about the Python-list mailing list