M
Mike Meyer
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__
find with no arguments is identical to the any function <URL:
http://www.artima.com/forums/flat.jsp?forum=106&thread=98196 > that
Guido has already accepted <URL:
http://mail.python.org/pipermail/python-dev/2005-March/052010.html >,
except it's a method.
find raises a ValueError so that you can search for any value. This
also keeps it's behavior similar to index.
An alternative to adding a new method to collections would be adding a
new keyword argument - test - to the list index method. This would
remove the overlap of functionality with any. However, it would also
mean you couldn't use it on anything but lists (and presumably
strings). I'm not sure how serious a restriction that is.
inject is basically an OO version of reduce. You can define it in
terms of reduce:
def inject(self, op, init = None):
return reduce(op, self, init)
The arguments against reduce probably apply to it as well. But it
makes the pain from removing reduce vanish.
These have probably been proposed before, but under other names. If
so, I'd appreciate pointers to the discussion.
<mike
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__
find with no arguments is identical to the any function <URL:
http://www.artima.com/forums/flat.jsp?forum=106&thread=98196 > that
Guido has already accepted <URL:
http://mail.python.org/pipermail/python-dev/2005-March/052010.html >,
except it's a method.
find raises a ValueError so that you can search for any value. This
also keeps it's behavior similar to index.
An alternative to adding a new method to collections would be adding a
new keyword argument - test - to the list index method. This would
remove the overlap of functionality with any. However, it would also
mean you couldn't use it on anything but lists (and presumably
strings). I'm not sure how serious a restriction that is.
inject is basically an OO version of reduce. You can define it in
terms of reduce:
def inject(self, op, init = None):
return reduce(op, self, init)
The arguments against reduce probably apply to it as well. But it
makes the pain from removing reduce vanish.
These have probably been proposed before, but under other names. If
so, I'd appreciate pointers to the discussion.
<mike