[Tutor] generator object
Peter Otten
__peter__ at web.de
Wed Aug 31 18:54:02 EDT 2016
Alan Gauld via Tutor wrote:
> On 31/08/16 08:56, Alan Gauld via Tutor wrote:
>
>> A generator function can return any kind of object including
>> basic types like numbers, bool etc.In addition, a generator
>> function yields values which can also be of any type.
>
> Hmmm.
> After reading Steven's response I played around a bit.
>
> While a generator function can indeed have a return
> value in it I'm not sure how one would use it.
>
> I tried:
>
> def gen(x):
> if x > 0: return 42
> else: yield x
>
> Then I tried
>
> x = gen(2)
> and
> x = list(2)
>
> But neither show any evidence of the return value.
>
> Can anyone provide a valid use-case for this feature?
>
> It definitely doesn't work the way I thought it did...
> But I've never needed to use return in a generator
> so never tried it before!
>
> What I expected/hoped it would do was act like a
> yield but also exit the function. No such luck.
>
> I can't even recall where I read about using returns
> in generator functions and what rationale was
> provided. It doesn't seem to be specifically
> discussed in the python docs. The only use I
> can see is to terminate the function immediately
> but the return value appears to disappear in smoke...
I don't have a use case, but here's how to retrieve the return value:
>>> def gen():
... return 42
... yield
...
>>> try: next(gen())
... except StopIteration as err: print(err.value)
...
42
More information about the Tutor
mailing list