On 11/29/2018 8:16 AM, E. Madison Bray wrote:

Okay, let's keep it simple:

m = map(str, [1, 2, 3])
len_of_m = None
if len(m.iters) == 1 and isinstance(m.iters[0], Sized):
     len_of_m = len(m.iters[0])

As I have noted before, the existing sized collection __length_hint__ methods (properly) return the remaining items = len(underlying_iterable) - items_already_produced. This is fairly easy at the C level. The following seems to work in Python.

class map1:
    def __init__(self, func, sized):
        "
        if isinstance(sized, (list, tuple, range, dict)):
            self._iter = iter(sized)
            self._gen = (func(x) for x in self._iter)
        else:
            raise TypeError(f'{size} not one of list, tuple, range, dict')
    def __iter__(self):
        return self
    def __next__(self):
        return next(self._gen)
    def __length_hint__(self):
        return __length_hint__(self._iter)

m = map1(int, [1.0, 2.0, 3.0])
print(m.__length_hint__())
print('first item', next(m))
print(m.__length_hint__())
print('remainer', list(m))
print(m.__length_hint__())
# prints, as expected and desired
3
first item 1
2
remainer [2, 3]
0

A package could include a version of this, possibly compiled, for use when applicable.

--
Terry Jan Reedy

_______________________________________________
Python-ideas mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to