Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value of a return after a yield in python [duplicate]

Tags:

python

yield

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
like image 335
Machkour Oke Avatar asked Nov 26 '22 19:11

Machkour Oke


1 Answers

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

like image 101
Olav Aga Avatar answered Dec 04 '22 16:12

Olav Aga