Proposed new collection methods
Christopher Subich
spam.csubich+block at block.subich.spam.com
Sat Aug 6 21:59:03 EDT 2005
Mike Meyer wrote:
> Another thread pointed out a couple of methods that would be nice to
> have on Python collections: find and inject. These are taken from
> <URL: http://martinfowler.com/bliki/CollectionClosureMethod.html >.
>
> find can be defined as:
>
> def find(self, test = None):
> for item in self:
> if test:
> if test(item):
> return item
> elif item:
> return item
> return ValueError, '%s.index(): no matching items in list' \
> % self.__class__.__name__
Dear Zeus no. Find can be defined as:
def find(self, test=lambda x:1):
try:
item = (s for s in iter(self) if test(s)).next()
except StopIteration:
raise ValueError('No matching items in list')
Let's use generators, people. And given the simplicity of writing this,
I'm not sure we need it in the standard library -- especially since the
default test is arbitrary. This recipe can also be useful for
dictionaries, where the syntax would be slightly different, and
lists-of-immutables, in which case returning the index in the list might
be better. Too much customization.
> inject is basically an OO version of reduce. You can define it in
> terms of reduce:
Except that if it's exactly reduce, we don't need to call it inject.
The problem with reduce in python isn't that it's functional rather than
OO, it's that it's limited to a function call or lambda -- one
expression rather than an anonymous block.
More information about the Python-list
mailing list