What can I use instead of next () in python 2.4

I need to emulate izip_longest

from itertools

in Python 2.4

import itertools
class Tools:
    @staticmethod
    def izip_longest(*args, **kwds):
        # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
        fillvalue = kwds.get('fillvalue')
        counter = [len(args) - 1]
        def sentinel():
            if not counter[0]:
                raise ZipExhausted
            counter[0] -= 1
            yield fillvalue
        fillers = itertools.repeat(fillvalue)
        iterators = [itertools.chain(it, sentinel(), fillers) for it in args]
        try:
        while iterators:
            yield tuple(map(next, iterators))
        except ZipExhausted:
            pass       


class ZipExhausted(Exception):
    pass

      

Everything works fine until it reaches yield tuple(map(next, iterators))

; Python 2.4 throws away

NameError: global name 'next' is not defined

      

error and shutdown.

What can I use instead next

to make it izip_longest

run in Python 2.4?

Or is there any other function in Python 2.4 that returns the same result as izip_longest()

?

+3


source to share


1 answer


The feature was added in Python 2.6. Use the method from iterators instead : next()

next

while iterators:
    yield tuple([it.next() for it in iterators])

      

or define your own function next()

; you are not using an argument default

, so for your simpler case:



def next(it):
    return it.next()

      

but the full version is:

_sentinel = object()

def next(it, default=_sentinel):
    try:
        return it.next()
    except StopIteration:
        if default is _sentinel:
            raise
        return default

      

+6


source







All Articles