New submission from Oscar Benjamin:
I've often wanted to be able to query a takewhile object to discover the item
that failed the predicate but the item is currently discarded.
A usage example:
def sum(items):
it = iter(items)
ints = takewhile(Integral.__instancecheck__, it)
subtotal = sum(ints)
if not hasattr(ints.lastitem):
return subtotal
floats = takewhile(float.__instancecheck__, it)
subtotalf = fsum(floats)
if not hasattr(floats.lastitem):
return subtotal + subtotalf
# Deal with more types
...
Loosely what I'm thinking is this but perhaps with different attribute names:
class takewhile(pred, iterable):
def __init__(self):
self.pred = pred
self.iterable = iterable
self.failed = False
def __iter__(self):
for item in self.iterable:
if self.pred(item):
yield item
else:
self.failed = True
self.lastitem = item
return
----------
components: Library (Lib)
messages: 195962
nosy: oscarbenjamin
priority: normal
severity: normal
status: open
title: Add .lastitem attribute to takewhile instances
type: enhancement
versions: Python 3.4
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue18821>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com