Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda