Do you have real-world use cases for map's None fill-in feature?

Paul Rubin http
Mon Jan 9 03:53:26 EST 2006

"Raymond Hettinger" <python at> writes:
> I am evaluating a request for an alternate version of itertools.izip()
> that has a None fill-in feature like the built-in map function:
> >>> map(None, 'abc', '12345')   # demonstrate map's None fill-in feature

I think finding different ways to write it was an entertaining
exercise but it's too limited in usefulness to become a standard

I do think some idiom ought to develop to allow checking whether an
iterator is empty, without consuming an item.  Here's an idea:
introduce something like

   iterator = check_empty(iterator)

where check_empty would work roughly like (untested):
   def check_empty(iterator):
      iclass = iterator.__class__
      class buffered(iclass):
         def __init__(self):
            n = iter((,))  # might raise StopIteration
            self.__save = chain(n, self)
         def next(self):
         # all other operations are inherited from iclass

      return buffered(iterator)

The idea is you get back a new iterator which yields the same stream
and supports the same operations as the old one, if the old one is
non-empty.  Otherwise it raises StopIteration.

There are some obvious problems with the above:

 1) the new iterator should support all of the old one's attributes,
    not just inherit its operations
 2) In the case where the old iterator is already buffered, the
    constructor should just peek at the lookahead instead of making
    a new object.  That means that checking an iterator multiple times
    won't burn more and more memory.

Maybe there is some way of doing the above with metaclasses but I've
never been able to wrap my head around those.

More information about the Python-list mailing list