Ian Fiddes
Ian Fiddes

Reputation: 3001

generator that does not necessarily yield anything

I want to have a generator that may or may not have anything to yield, and if .next() or similar is used it will not have a StopIteration error if none of the conditions to yield are met.

An example:

def A(iterable):
    for x in iterable:
        if x == 1:
           yield True

Which works like the following:

>>> list(A([1,2]))
[True]
>>> A([1]).next()
True
>>> A([2]).next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

But what I would want is for A([2]).next() to return is None.

Upvotes: 1

Views: 71

Answers (2)

mgilson
mgilson

Reputation: 309929

generally, in these circumstances you'd use the builtin next function:

my_iterator = A([2])
value = next(my_iterator, None)

In addition to being able to pass an optional "default" value when the iterator is empty, next has the advantage of working on python2.x and python3.x where the name of the method changes to __next__.

Upvotes: 2

Brent Washburne
Brent Washburne

Reputation: 13158

How about this:

def A(iterable):
    for x in iterable:
       yield True if x == 1 else None

Upvotes: 1

Related Questions