python generator with check for empty condition

Viewed 10974

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 to write a wrapper which will allow checking for empty condition but is still lazy and gives the benefit of generators.

class mygen:
  def __init__(self,iterable):
    self.iterable = (x for x in iterable)
    self.peeked = False
    self.peek = None
  def __iter__(self):
    if self.peeked:
      yield self.peek
      self.peeked = False
    for val in self.iterable:
      if self.peeked:
        yield self.peek
        self.peeked = False
      yield val
    if self.peeked:
      yield self.peek
      self.peeked = False
  def __nonzero__(self):
    if self.peeked:
      return True
    try:
      self.peek = self.iterable.next()
      self.peeked = True
      return True
    except:
      return False
  1. I think it behaves correctly like a plain generator. Is there any corner case I'm missing?
  2. This doesn't look elegant. Is there a better more pythonic way of doing the same?

Sample usage:

def get_odd(l):
    return mygen(x for x in l if x%2)

def print_odd(odd_nums):
  if odd_nums:
      print "odd numbers found",list(odd_nums)
  else:
      print "No odd numbers found"

print_odd(get_odd([2,4,6,8]))
print_odd(get_odd([2,4,6,8,7]))
2 Answers
Related