[Python-ideas] x=(yield from) confusion [was:Yet another alternative name for yield-from]

Nick Coghlan ncoghlan at gmail.com
Wed Apr 8 13:34:40 CEST 2009


Jacob Holm wrote:
> That would have been correct if my statement about what was needed
> wasn't missing a bit.  What you actually need to replace with is
> something like:
> 
> def example(start, *args, **kw):
>    ...
>    if 'throw' in start:
>        raise start['throw'] # simulate a throw() on first next()
>    elif 'send' in start:
>        x = start['send']    # simulate a send() on first next()
>    else:
>        x = yield start.get('yield')  # use specified value for first next()

This elaboration strikes me as completely unecessary, since next() or
the equivalent send(None) are the only legitimate ways to start a generator:

>>> def gen():
...   print "Generator started"
...   yield
...
>>> g = gen()
>>> g.next()
Generator started

A generator that receives a throw() first thing never executes at all:

>>> g = gen()
>>> g.throw(AssertionError)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in gen
AssertionError

Similarly, sending a non-None value first thing triggers an exception
since there is nowhere for the value to go:

>>> g = gen()
>>> g.send(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't send non-None value to a just-started generator

For the PEP, I think the solution to this issue is a couple of conventions:

1. Either don't implicitly call next() when creating coroutines or else
make that behaviour easy to bypass). This is a bad idea for the same
reason that implicitly calling start() on threads is a bad idea:
sometimes the user will want to separate definition from activation, and
it is a pain when the original author makes that darn near impossible in
order to save one line in the normal case.

2. Coroutines intended for use with yield-from should take a "start"
argument that is used for the value of their first yield. This allows
coroutines to be nested without introducing spurious "None" values into
the yield stream.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list