Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to have a function output a generator expression and a value at the same time

I wanted to have one function output a generator expression as well as a value (string, integer, list, tuple, etc.), I tried a making one, it looked like this:

def func():
    for x in range(3):
        yield x
    return "Hello World"

print(func())

I ran debug, it seems to run the return but doesn’t output anything when I print the result

<generator object func at 0x7fb35a69ac80>

why is this happening and how can I solve this issue of it running the return statement but not returning anything.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The return value in a generator is expressed as part of the data in the StopIteration exception. This exception occurs when you call next on a generator that has exhausted all of its remaining values.

Here is a brief example of how it can be used.

def func():
    for x in range(3):
        yield x
    return "Hello World"

gen = func()

try:
    while True:
        print(next(gen))
except StopIteration as e:
    print(e.value)
0
1
2
Hello World
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading