python generator with check for empty condition

前端 未结 2 1286
孤城傲影
孤城傲影 2021-02-13 21:53

python generators are good replacements for lists in most cases expect where I would like to check for empty condition which is not possible with plain generators. I am trying t

2条回答
  •  感情败类
    2021-02-13 22:55

    I would not usually implement this kind of generator. There is an idiomatic way how to test if a iterator it is exhausted:

    try:
        next_item = next(it)
    except StopIteration:
        # exhausted, handle this case
    

    Substituting this EAFP idiom by some project-specific LBYL idiom seems confusing and not beneficial at all.

    That said, here is how I would implement this if I really wanted to:

    class MyIterator(object):
        def __init__(self, iterable):
            self._iterable = iter(iterable)
            self._exhausted = False
            self._cache_next_item()
        def _cache_next_item(self):
            try:
                self._next_item = next(self._iterable)
            except StopIteration:
                self._exhausted = True
        def __iter__(self):
            return self
        def next(self):
            if self._exhausted:
                raise StopIteration
            next_item = self._next_item
            self._cache_next_item()
            return next_item
        def __nonzero__(self):
            return not self._exhausted
    

提交回复
热议问题