[New-bugs-announce] [issue18821] Add .lastitem attribute to takewhile instances

Oscar Benjamin report at bugs.python.org
Fri Aug 23 14:19:54 CEST 2013

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
                self.failed = True
                self.lastitem = item

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 <report at bugs.python.org>

More information about the New-bugs-announce mailing list