[Python-ideas] yield-from and @coroutine decorator [was:x=(yield from) confusion]
ncoghlan at gmail.com
Sat Apr 4 14:29:00 CEST 2009
Jacob Holm wrote:
> Yet another fix that requires no extra syntax would be to store the
> latest value yielded by the generator in a property on the generator
> (raising AttributeError before the first yield). Then the initial:
> _y = _i.next()
> could be replaced with:
> _y = _i.gi_latest_yield # or whatever its name would be.
> except AttributeError:
> _y = _i.next()
> The benefit of this version is that it requires no new syntax, it avoids
> the extra next() call for coroutines, and it opens some new ways of
> using generators. It also supports almost everything that would be
> possible with the syntax-based fix. (Everything if the property is
> actually writable, but I don't really see a use for that except perhaps
> for deleting it).
> I can even remember that I have wanted such a property before, although
> I don't recall the exact use case.
> One bad thing about it is that the initial yield made by the yield-from
> is then the value that the coroutine decorator was meant to discard
> (usually None). That might be a reason for allowing the property to be
> writable, or for a change in syntax after all. On the other hand, if
> this is a problem you can manually call the coroutine the way you want
> before using it in yield-from, which would then initialize the value
> exactly like with the second syntax idea.
> Of the three ideas so far, I much prefer the one without extra syntax.
This issue is still bouncing around in my brain, so I don't have a lot
say about it yet, but a special attribute on the generator-iterator
object that the yield from expression could check was the first possible
approach that occurred to me.
Although, rather than it being the "latest yield" from the generator, I
was thinking more of just an ordinary attribute that a @coroutine
decorator could set to indicate what to yield when firing it up with
On your syntax ideas, note that the parser can't do anything tricky with
expressions of the form "yield EXPR" - the parser will treat that as a
normal yield and get confused if you try to add anything after it.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas