dict generator question

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Sep 23 04:10:35 CEST 2008

Steven D'Aprano:

>I'm sorry, I don't recognise leniter(). Did I miss something?<

I have removed the docstring/doctests:

def leniter(iterator):
    if hasattr(iterator, "__len__"):
        return len(iterator)
    nelements = 0
    for _ in iterator:
        nelements += 1
    return nelements

>it doesn't work for arbitrary iterables, only sequences (lazy or otherwise)<

I don't understand well.

>Since you're generating the entire length anyway, len(list(iterable)) is more readable and almost as efficient for most practical cases.<

I don't agree, len(list()) creates an actual list, with lot of GC

>But the expected semantics of __len__ is that it is expected to return an int, and do it quickly with minimal effort. Methods that do something else are an abuse of __len__ and should be treated as a bug.<

I see. In the past I have read similar positions in discussions
regarding API of data structures in D, so this may be right, and this
fault may be enough to kill my proposal. But I'll keep using


More information about the Python-list mailing list