question about generators

Tim Peters tim at zope.com
Fri Aug 16 19:00:19 CEST 2002


[Neil Schemenauer]
> I think that depends on how 'yield every' works.

I thought of it as pure syntactic sugar,

    yield every expr

same-as

    for _tempname in expr:
        yield _tempname

where _tempname is an internal vrbl name that doesn't conflict with any
other vrbl name.

> Does it require a generator-iterator or just any iterator?

By definition, the semantics are exactly the same as in the "for" loop
rewrite.  So, for example,

    yield every [1, 2, 3]

would yield 1, then yield 2, then yield 3, because that's what

    for x in [1, 2, 3]:
        yield x

does today.  So expr must evaluate to an iterable object, and that's the
only requirement.  A generator-iterator is one kind of iterable object, of
course.

Note that

    yield every 666

would raise an exception, because

    for x in 666:

raises one today.

> Also, does it allow the generator-iterator to be passed?

Couldn't parse that one.

>  For example,
>
>     def grange(n):
>         for i in xrange(n):
>            yield i
>
>     def grange_wrapper():
>         return grange()
>
>     def a():
>         yield every grange(10)
>
>     def b():
>         yield every grange_wrapper(10)

Since grange_wrapper() above doesn't accept an argument, it's unclear
whether you're asking about exception behavior here.

>     def c():
>         yield every range(10)
>
> do 'a', 'b', 'c' all work?

If you think these "work" today (grange_wrapper() really muddied your
intent -- you're passing it an argument but it doesn't accept one, while it
in turn doesn't pass an argument to a function that requires one), yes, else
no:

def aa():
    for x in grange(10):
        yield x

def bb():
    for x in grange_wrapper(10):
        yield x

def cc():
    for x in range(10):
        yield x





More information about the Python-list mailing list