Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
empty generator
#1
coding a generator. but what if it has nothing to yield? just return? return anything in particular?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
As per PEP255, empty return statement is allowed in the generator function

borrowing the example from pep255
def f1():
    try:
        return
    except:
        yield 1

print('Loop over empty generator')
for item in f1():
    print(item)
print('Loop over empty generator completed')

print('call next() on empty generator')
next(f1())
Output:
Loop over empty generator Loop over empty generator completed call next() on empty generator Traceback (most recent call last): File "***", line **, in <module> next(f1()) StopIteration
or without return

def empty_generator():
    for item in []:
        yield item

print('Loop over empty generator')

for item in empty_generator():
    print(item)

print('Loop over empty generator completed')

print('call next() on empty generator')
next(empty_generator())
Output:
Loop over empty generator Loop over empty generator completed call next() on empty generator Traceback (most recent call last): File "***", line **, in <module> next(empty_generator()) StopIteration
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
This one works too
>>> def foo():
...     if False: yield
... 
>>> list(foo())
[]
>>> 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  receive from a generator, send to a generator Skaperen 9 5,527 Feb-05-2018, 06:26 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020