Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Getting the value of a return after a yield in python

I would like to know how to get the return value of a function after all the execution of yield in a function like this:

def gen_test():
    l = []
    for i in range(6):
        l.append(i)
        yield i
    # i want to know this value after all iteration of yield
    return l
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

The short version is that it is not allowed. Passing values with the return statement in generators causes an error in python prior to version 3.3. For these versions of Python, return can only be used without an expression list and is equivalent to raise StopIteration.

For later versions of Python, the returned values can be extracted through the value-attribute of the exception.

You can find more information about this here: Return and yield in the same function

over 4 years ago · Santiago Trujillo Report

0

The return value of your iterator function is used as the argument to the StopIteration that it raises when it terminates:

>>> it = gen_test()
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
5
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration: [0, 1, 2, 3, 4, 5]

Only the first StopIteration gets the specified value. Further attempts to iterate an empty generator will raise an empty exception:

>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

You can extract the return value from a normal run of the iterator by avoiding for loops and trapping the exception yourself:

it = gen_test()
while True:
    try:
        x = next(it)
        # Do the stuff you would normally do in a for loop here
    except StopIteration as e:
        ret = e.value
        break
print(ret)

All this is an awkward approach given that you have to decide between not using for loops and not being able to return your accumulated data. Assuming that you're not OK with trying to accumulate the data externally (e.g. just doing list(gen_test())), you can make your generator's state publicly accessible by using a class:

class gen_test:
    def __init__(self):
        self.l = []
        self.it = iter(range(6))

    def __iter__(self):
        return self

    def __next__(self):
        i = next(self.it)
        self.l.append(i)
        return i

Now you can do something like

>>> it = gen_test()
>>> for x in it:
...     print(x)
0
1
2
3
4
5
>>> print(it.l)
[0, 1, 2, 3, 4, 5]
over 4 years ago · Santiago Trujillo Report

0

The presence of yield in your function turns it into something different than a regular function - python calls it a generator. You can not call a generator and expect it to preform like a function. Except perhaps in a degenerate or simplistic case. To retrieve state information ( like the whole list l ) in your question at the end of the generator life, you need to store in in a variable or return it every time in the yield statement.

To return it every time the generator is called do this:

def gen_test():
    l = []
    for i in range(6):
        l.append(i)
        yield i, l
    
for y,l in gen_test():
        print (y,l)
    

Otherwise you could declare your generator as part of a class and store intermediate results in a class variable. Then retrieve that variable value using a different call later.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!