generator object or 'send' method?
andrew cooke
andrew at acooke.org
Mon Feb 9 15:07:41 EST 2009
If I were experimenting with Python to see just how far I could push
coroutines at the moment, I would use .send() and look at how I could
factor things into a small library (containing, for example, your
trap-and-response secondary generator).
But if this was paid work, I would write a class with a __next__ method
and do things explicitly.
In answer to your PS, via a roundabout route: I've done something similar
recently by using .throw() to raise an exception in the body of the
generator. This was done with a reset() function. So, for example:
mygen = ...
a = next(mygen)
b = next(mygen)
reset(mygen)
c = next(mygen)
And in the generator:
while True:
try:
...
yield ...
catch ResetException:
yield # discarded by the reset function
And finally:
def reset(gen):
gen.throw(ResetException())
In that case, I needed an extra "yield" that did nothing.
Andrew
Aaron Brady wrote:
> Hello,
>
> I am writing a generator to return a sequence of numbers with some
> variation. The parameters of the variation can be changed by the
> caller, even after the generator is started. My question is, is it
> better to wrap the generator in an object, so that the parameters can
> be changed just by an attribute access? Or keep the generator clear,
> and modify parameters with a 'send' call?
>
> P.S. It would receive the 'send' from a different point in control
> flow than its usual 'next'. Should it repeat a value if it receives a
> 'send'? Or should I wrap it in a secondary 'trap_send_and_repeat'
> generator?
>
> Thanks sincerely as always.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
More information about the Python-list
mailing list