can generators be nested?

Michael Sparks zathras at thwackety.com
Thu Aug 28 07:38:27 EDT 2003


Hi,


Unfortunately there isn't a way of doing this - the reason is that the act
of including the yield keyword in a function/method definition turns the
function/method definition into a generator definition.

The way you're doing it now:
>    for i in gen2(): yield i

Is the only way of doing it.

I asked essentially the same question almost a year ago - I was concerned
about the fragility of nesting yields.

The fact you can't do this influenced certain aspects on the design of a
system I'm working on for work - largely to shield users of my classes
from the problem.

The original thread where I asked the question is here:
   * http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=alqehl%249qv%241%40nntp0.reith.bbc.co.uk&rnum=9&prev=/&frame=on

Best Regards,


Michael



On Wed, 27 Aug 2003, news.west.cox.net wrote:

> This doesn't work, but is there any elegant way to do something like this?
>
> def gen2():
>    yield "hello"
>
> def gen1():
>    gen2()
>    yield "world"
>
> for i in gen1(): print i
>
> ---- output ----
> hello
> world
>
> I'm doing it this way now:
>
> def gen2():
>    yield "hello"
>
> def gen1():
>    for i in gen2(): yield i
>    yield "world"
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>






More information about the Python-list mailing list