Generator Question

G

GZ

Hi,

I am wondering what would be the best way to return an iterator that
has zero items.

I just noticed the following two are different:

def f():
pass
def g():
if 0: yield 0
pass

for x in f(): print x
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
TypeError: 'NoneType' object is not iterable

for x in g(): print x
#loop exits without any errors

Now the question here is this:

def h():
if condition=true:
#I would like to return an itereator with zero length
else:
for ...: yield x

In other words, when certain condition is met, I want to yield
nothing. How to do?

Thanks,
gz
 
S

Steven D'Aprano

Hi,

I am wondering what would be the best way to return an iterator that has
zero items.

return iter([])

I just noticed the following two are different:

def f():
pass

That creates a function that does nothing, and then returns None (because
Python doesn't have Pascal procedures or C void function).

def g():
if 0: yield 0
pass

The pass is redundant.

This creates a generator function which, when called, doesn't yield
anything, then raises StopIteration.
 
C

Chris Angelico

def h():
   if condition=true:
      #I would like to return an itereator with zero length
   else:
      for ...: yield x

Easy. Just 'return' in the conditional.
if condition:
return
for i in range(4): yield i

A generator object is returned since the function contains a 'yield'.
On one of the branches, nothing will ever be yielded and StopIteration
will be raised immediately.

You could probably also raise StopIteration directly, but it's not necessary.

ChrisA
 
S

Steven D'Aprano

Now the question here is this:

def h():
if condition=true:
#I would like to return an itereator with zero length
else:
for ...: yield x

In other words, when certain condition is met, I want to yield nothing.
How to do?

Actually, there's an even easier way.
.... if not condition:
.... for c in "abc":
.... yield c
....
condition = False
list(h()) ['a', 'b', 'c']
condition = True
list(h())
[]
 
G

GZ

I see. Thanks for the clarification.

Now the question here is this:
def h():
    if condition=true:
       #I would like to return an itereator with zero length
    else:
       for ...:yieldx
In other words, when certain condition is met, I want toyieldnothing.
How to do?

Actually, there's an even easier way.

...     if not condition:
...         for c in "abc":
...            yieldc
...
condition = False
list(h()) ['a', 'b', 'c']
condition = True
list(h())

[]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top